The DOM MutationObserver()
constructor — part of the MutationObserver
interface — creates and returns a new observer which invokes a specified callback when DOM events occur.
DOM observation does not begin immediately; the observe()
method must be called first to establish which portion of the DOM to watch and what kinds of changes to watch for.
new MutationObserver(callback)
A new MutationObserver
object, configured to call the specified callback
when DOM mutations occur.
This example creates a new MutationObserver
configured to watch a node and all of its children for additions and removals of elements to the tree, as well as any changes to attributes on any of the elements in the tree.
function callback(mutationList, observer) {
mutationList.forEach( (mutation) => {
switch(mutation.type) {
case 'childList':
break;
case 'attributes':
break;
}
});
}
The callback()
function is invoked when the observer sees changes matching the configuration of the observation request specified when calling observe()
to begin watching the DOM.
The kind of change that took place (either a change to the list of children, or a change to an attribute) is detected by looking at the mutation.type
property.
This code actually sets up the observation process.
const targetNode = document.querySelector("#someElement");
const observerOptions = {
childList: true,
attributes: true,
subtree: true
}
const observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);
The desired subtree is located by finding an element with the ID someElement
. A set of options for the observer is also established in the observerOptions
record. In it, we specify values of true
for both childList
and attributes
, so we get the information we want.
Then the observer is instantiated, specifying the callback()
function. We begin observing the DOM nodes of interest by calling observe()
, specifying the target
node and the options
object.
From this point until disconnect()
is called, callback()
will be called each time an element is added to or removed from the DOM tree rooted at targetNode
, or any of those elements' attributes are changed.