The MutationObserver
interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.
MutationObserver()
MutationObserver
which will invoke a specified callback function when DOM changes occur.disconnect()
MutationObserver
instance from receiving further notifications until and unless observe()
is called again.observe()
MutationObserver
to begin receiving notifications through its callback function when DOM changes matching the given options occur.takeRecords()
MutationObserver
's notification queue and returns them in a new Array
of MutationRecord
objects.https://codepen.io/webgeeker/full/YjrZgg/
The following example was adapted from this blog post.
// Select the node that will be observed for mutations var targetNode = document.getElementById('some-id'); // Options for the observer (which mutations to observe) var config = { attributes: true, childList: true, subtree: true }; // Callback function to execute when mutations are observed var callback = function(mutationsList, observer) { for(var mutation of mutationsList) { 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 function var observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(targetNode, config); // Later, you can stop observing observer.disconnect();
Specification | Status | Comment |
---|---|---|
DOM The definition of 'MutationObserver' in that specification. | Living Standard |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 26
|
Yes | 14 | 11 | 15 | 7
|
MutationObserver() constructor |
26
|
Yes | 14 | 11 | 15 | 7
|
observe |
18 | Yes | 14 | 11 | 15 | 6 |
disconnect |
18 | Yes | 14 | 11 | 15 | 6 |
takeRecords |
18 | Yes | 14 | 11 | 15 | 6 |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes
|
26
|
Yes | 14 | 14 | 7
|
Yes |
MutationObserver() constructor |
Yes
|
26
|
Yes | 14 | 14 | 7
|
Yes |
observe |
Yes | 18 | Yes | 14 | 14 | 6 | Yes |
disconnect |
Yes | 18 | Yes | 14 | 14 | 6 | Yes |
takeRecords |
Yes | 18 | Yes | 14 | 14 | 6 | Yes |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver