MutationObserver
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheMutationObserver interface provides the ability to watch for changes being made to theDOM tree. It is designed as a replacement for the olderMutation Events feature, which was part of the DOM3 Events specification.
In this article
Constructor
MutationObserver()Creates and returns a new
MutationObserverwhich will invoke a specified callback function when DOM changes occur.
Instance methods
disconnect()Stops the
MutationObserverinstance from receiving further notifications until and unlessobserve()is called again.observe()Configures the
MutationObserverto begin receiving notifications through its callback function when DOM changes matching the given options occur.takeRecords()Removes all pending notifications from the
MutationObserver's notification queue and returns them in a newArrayofMutationRecordobjects.
Example
The following example was adapted fromthis blog post.
// Select the node that will be observed for mutationsconst targetNode = document.getElementById("some-id");// Options for the observer (which mutations to observe)const config = { attributes: true, childList: true, subtree: true };// Callback function to execute when mutations are observedconst callback = (mutationList, observer) => { for (const mutation of mutationList) { if (mutation.type === "childList") { console.log("A child node has been added or removed."); } else if (mutation.type === "attributes") { console.log(`The ${mutation.attributeName} attribute was modified.`); } }};// Create an observer instance linked to the callback functionconst observer = new MutationObserver(callback);// Start observing the target node for configured mutationsobserver.observe(targetNode, config);// Later, you can stop observingobserver.disconnect();Specifications
| Specification |
|---|
| DOM> # interface-mutationobserver> |