Mutation Observer API
The mutationObserver
function creates a MutationObserver
instance that watches for changes in the DOM tree.
const observer = mutationObserver(target, options)
Parameters
Parameter | Type | Description |
---|---|---|
target | Element Element[] NodeList Window | The element(s) to observe. If Window is passed, it will observe document.body instead. |
options | object | Configuration options for the observer |
Options
Option | Type | Default | Description |
---|---|---|---|
callback | function | - | Function called when mutations occur. Receives { entry, entries, observer } |
attributes | boolean | false | Whether to observe attribute changes |
childList | boolean | false | Whether to observe changes to the target’s children |
subtree | boolean | false | Whether to observe changes to the target’s descendants |
attributeFilter | string[] | - | Array of attribute names to observe. Only used if attributes is true |
attributeOldValue | boolean | false | Whether to record the previous value of attributes |
characterData | boolean | false | Whether to observe changes to the target’s data |
characterDataOldValue | boolean | false | Whether 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:
Property | Type | Description |
---|---|---|
entry | MutationRecord | The current mutation record being processed |
entries | MutationRecord[] | All mutation records being observed |
observer | MutationObserver | The observer instance |
Return Value
Returns an object with the following methods:
Method | Parameters | Return Value | Description |
---|---|---|---|
observe | Element 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})