introduce
MutationObserver gives developers the ability to react appropriately to changes in a DOM tree within a range. This API is designed to replace Mutation events introduced in the DOM3 event specification.
The above quote comes from the authoritative MDN. (Too lazy to write my own…)
Create a MutationObserver object
var mo = new MutationObserver(
function callback
);
Copy the code
There is only one argument, the callback, which is triggered when the MutationObserver listens for a change in the target. The callback argument is passed two arguments. The first is a parameter containing information about several change targets, called a MutationRecord object. The second argument is the object you created itself.
Instance methods
1. Observe () :
Observe (Node, option); // Observe (Node, option);Copy the code
The Option object can be configured to listen on children of the target node and HTML attributes/text. See MutationObserverInit for more details
2. Disconnect () Stops listening.
3. TakeRecords () clears the observer’s record queue and returns its contents
compatibility
A case in point
The following example demonstrates how to insert a node periodically and be monitored.
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta http-equiv=" x-UA-compatible "content="ie=edge"> <title>MutationObserver demo</title> </head> <body> <div id="info" style="color:brown; font-size: 20px;" <div >< div id="wrap"></div> <script> var info = document.getElementById('info'); main(); / / create MutationObserver object and the callback function createMutationObserverObject () {var MutationObserver = window. MutationObserver | | window.WebKitMutationObserver || window.MozMutationObserver; if(! MutationObserver){info.innerhtml = 'Your browser does not support MutationObserver objects! '; return false; } return new MutationObserver(function(mutations) {mutations. ForEach (function(mutation) {info.innerhtml = ' Id of the new element: '+ mutation. AddedNodes [0]. }); }); } / / using MutationObserver object observe method to the target node to monitor function listen () {var observer = createMutationObserverObject (); if(! observer) return; observer.observe(wrap, { attributes: true, childList: true}); } function main(){listen(); var count = 0; var listenDom = setInterval(function(){ count++; var p = document.createElement('p'); p.id = 'p' + count; P.innertext = "my id is p" + count; wrap.appendChild(p); if(count>=5){ clearInterval(listenDom); //observer.disconnect(); } }, 1500) } </script> </body> </html>Copy the code