Mutation Observer API

The mutationObserver function creates a MutationObserver instance that watches for changes in the DOM tree.

const observer = mutationObserver(target, options)

Parameters

ParameterTypeDescription
targetElement
Element[]
NodeList
Window
The element(s) to observe. If Window is passed, it will observe document.body instead.
optionsobjectConfiguration options for the observer

Options

OptionTypeDefaultDescription
callbackfunction-Function called when mutations occur. Receives { entry, entries, observer }
attributesbooleanfalseWhether to observe attribute changes
childListbooleanfalseWhether to observe changes to the target’s children
subtreebooleanfalseWhether to observe changes to the target’s descendants
attributeFilterstring[]-Array of attribute names to observe. Only used if attributes is true
attributeOldValuebooleanfalseWhether to record the previous value of attributes
characterDatabooleanfalseWhether to observe changes to the target’s data
characterDataOldValuebooleanfalseWhether to record the previous value of character data

For more details about these options, see the MDN documentation.

Callback Parameters

When a mutation occurs, the callback receives an object with:

PropertyTypeDescription
entryMutationRecordThe current mutation record being processed
entriesMutationRecord[]All mutation records being observed
observerMutationObserverThe observer instance

Return Value

Returns an object with the following methods:

MethodParametersReturn ValueDescription
observeElement
Element[]
NodeList
-Starts observing new elements for mutations
takeRecords-MutationRecord[]Returns all pending mutation records and clears the queue
disconnect--Stops observing all elements, processes any pending records through the callback, and then disconnects the observer
destroy--Alias for disconnect().

Event Listener Alternative

If no callback is provided, the observer will dispatch a mutate event on the target element. You can listen for this event:

element.addEventListener('mutate', ({ detail }) => {
const { entry, entries, observer } = detail
// Handle mutation
})