In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "MutationObServer monitoring DOM element example analysis in JavaScript". In daily operation, I believe that many people have doubts about MutationObServer monitoring DOM element example analysis in JavaScript. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "MutationObServer monitoring DOM element example analysis in JavaScript". Next, please follow the editor to study!
I. basic use
It can be instantiated through the MutationObserver constructor, and the argument is a callback function.
Let observer = new MutationObserver (() = > console.log ("change")); console.log (observer)
The observer object prototype chain is as follows:
MutationObserver instance:
You can see that there are disconnect, observer, takeRecords methods.
1. Observer method listening
The observer method is used to associate DOM elements and listen according to the relevant settings.
The syntax is as follows:
/ / receive two parameters observer (DOM element, MutationObserverInit object)
Where:
The first parameter DOM element is the page element, such as body, div, and so on.
The second parameter is to set the range to listen on. For example, attributes, text, child nodes, etc., are an array of key-value pairs.
Example 1, listening for changes in the body element class:
Let observer = new MutationObserver (() = > console.log ("change")); / / listening for attribute changes of body element observer.observe (document.body, {attributes: true}); / / changing the class of body element will asynchronously execute the callback function document.body.className = "main" passed when the MutationObserver object is created; console.log ("body attribute modified"); / / console output: / / modified body attribute / / change
The output of the above change is after modifying the body property, so it can be seen that the registered callback function is executed asynchronously and later.
two。 Callback function adds MutationRecord instance array parameters
Now the callback function is very simple, just output a string, you can't see what's going on.
In fact, the callback function receives an array of MutationRecord instances, which can be used to view detailed information in practice.
Let observer = new MutationObserver (/ / the callback function is an array of MutationRecord instances. The format is as follows: / / [MutationRecord,...] (mutationRecords) = > console.log (mutationRecords); observer.observe (document.body, {attributes: true}); document.body.className = "main"; console.log ("modified body attribute"); / / console output: / / modified body attribute / / (1) [MutationRecord]
The mutationRecords information is as follows:
MutationRecord instance:
Some of the key messages are:
AttributeName represents the name of the modified attribute
Target of target modification
Type Typ
If you modify the properties of body multiple times, there will be multiple records:
/ / MutationRecordlet observer = new MutationObserver (/ / the callback function receives an MutationRecord instance, which is an array. (mutationRecords) = > console.log (mutationRecords); observer.observe (document.body, {attributes: true}); / / modify document.body.className = "main"; document.body.className = "container"; document.body.className = "box"; / / console print as follows: / / (3) [MutationRecord, MutationRecord, MutationRecord]
Note:
Instead of performing a callback for each modification, a MutationRecord instance is added to the mutationRecords parameter for each modification, and a callback is finally executed to print it out.
If you perform a callback one at a time, the performance will be poor.
3. Disconnect method terminates callback
If you want to terminate the callback, you can use the disconnect method.
Let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); observer.observe (document.body, {attributes: true}); / / first modification document.body.className = "main"; / / terminate observer.disconnect (); / / second modification document.body.className = "container"; / / No log output
There is no log output, including the first modification and no log output, because the callback function is executed asynchronously and at the end. The observer is terminated later, so it will not be executed.
You can use setTimeout control to terminate last, so that the callback will execute normally.
Let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); observer.observe (document.body, {attributes: true}); / / modify document.body.className = "main" for the first time; / / terminate setTimeout (() = > {observer.disconnect ()); / / the third modification will not call back document.body.className = "container";}, 0); / / modify document.body.className = "container" for the second time / / Page output: / / (2) [MutationRecord, MutationRecord]
Enable after termination
You can start again after termination, as shown in the following example:
Let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); observer.observe (document.body, {attributes: true}); / / the first modification will enter the mutationRecords array document.body.className = "main"; / / terminate setTimeout (() = > {observer.disconnect (); / / the second modification, because terminated, the following modifications will not enter the mutationRecords array document.body.className = "container";}, 0) SetTimeout (() = > {/ / enable observer.observe (document.body, {attributes: true}) again; / / modify the body attribute to enter the mutationRecords array document.body.className = "container";}, 0); / / console output: / / [MutationRecord] / / [MutationRecord]
The callback function here is executed twice, and two are printed, of which:
The first output is modified for the first time, and then there is no synchronization code, so the callback is executed.
The second output was modified for the third time, and the callback was executed normally because it was re-enabled.
The second modification, because observer was terminated, so modifying the properties of body will not be included in the mutationRecords array.
4. Obtain the modification record by takeRecords method
If you want to process an existing observer record before terminating the mutationRecords, you can get it with the takeRecords method.
Let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); observer.observe (document.body, {attributes: true}); / / the first modification will enter the mutationRecords array document.body.className = "main"; / / the second modification will enter the mutationRecords array document.body.className = "container"; / / the third modification will include the mutationRecords array document.body.className = "box" / / get the modification record, you can process it let mutationRecords = observer.takeRecords (); console.log (mutationRecords); / / console print: / / 3) [MutationRecord, MutationRecord, MutationRecord] console.log (observer.takeRecords ()); / / console print: / / [] / / terminate observer.disconnect (); second, monitor multiple elements
All of the above listeners have only one element. If you want to listen to multiple elements, you can reuse MutationObserver instances.
Let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); / / create the div1 element and listen to let div1 = document.createElement ("div"); observer.observe (div1, {attributes: true}); div1.id = "box1"; / / create div2 and listen for let div2 = document.createElement ("div"); observer.observe (div2, {attributes: true}); div2.id = "box2" / / console print: / / (2) [MutationRecord, MutationRecord]
The console prints two MutationRecord, where:
The first MutationRecord is the id property modification record of div1.
The second MutationRecord is the id property modification record of div2.
Other uses are similar to those above.
3. Listening scope MutationObserverInit object
The above listeners are listening properties, of course, you can also listen to other things, such as text, child nodes, and so on.
1. Observation attribute
The above examples are to observe the attributes of the element, and here is another example of a custom attribute.
Let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); observer.observe (document.body, {attributes: true}); / / modify custom attribute document.body.setAttribute ("data-id", 1); / / console print: / / [MutationRecord]
Modifying custom properties will also add to the mutationRecords array.
Another value mentioned is that data-id is often used to mark elements with some data or something, if there is a change, the program can listen and deal with some corresponding logic.
AttributeFilter filtering:
If you want to listen for specified property changes, you can use attributeFilter filtering.
Let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); observer.observe (document.body, {attributes: true, / / set whitelist attributeFilter: ["data-id"]}); / / modify attributes in whitelist attributeFilter and enter mutationRecordsdocument.body.setAttribute ("data-id", 1); / / modify attributes that are not in whitelist attributeFilter and do not enter mutationRecordsdocument.body.setAttribute ("class", "main") / / console print: / / [MutationRecord]
AttributeOldValue records old values:
If you want to record the old value, you can set attributeOldValue to true.
Let observer = new MutationObserver (oldValue in / / MutationRecord object represents the old value (mutationRecords) = > console.log (mutationRecords.map ((x) = > x.oldValue)); observer.observe (document.body, {attributes: true, attributeOldValue: true,}); / / the first modification, because there is no value, so the old value oldValue = nulldocument.body.setAttribute ("class", "main") / / the second modification, because there was a change before, so the old value oldValue = maindocument.body.setAttribute ("class", "container"); / / console print: / / (2) [null, 'main'] 2. Observe the text
Observe the text and set the characterData to true, but only the text nodes can be observed.
Take a look at the following example:
Hello let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); / / get text node let textNode = document.getElementById ("box"). ChildNodes [0]; observer.observe (textNode, {/ / observe text changes characterData: true}); / / modify text textNode.textContent = "Hi"; / / console print: / / [MutationRecord]
If you listen to the div element directly, it will not take effect:
Hello let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); / / listening div will not take effect let box = document.getElementById ("box"); observer.observe (box, {characterData: true}); box.textContent = "Hi"; / / there is no output on the console
CharacterDataOldValue records old values:
If you want to record the old value of the text, you can set characterDataOldValue to true.
Hello let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords.map ((x) = > x.oldValue); / / get text node let textNode = document.getElementById ("box"). ChildNodes [0]; observer.observe (textNode, {/ / observe text changes characterData: true, / / retain old data characterDataOldValue: true,}) / / modify the text twice textNode.textContent = "Hi"; textNode.textContent = "Nice"; / / console print: / / (2) ['Hello',' Hi']
Because the content in div was originally Hello, first changed to Hi, then changed to Nice, so the old values of the two modifications are: Hello and Hi.
3. Observe child nodes
The MutationObserver instance can also observe the changes of the target node child nodes.
Hello let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); / / get div let box = document.getElementById ("box"); observer.observe (box, {/ / observe child node changes childList: true,}); / / add element let span = document.createElement ("span") span.textContent = "world"; box.appendChild (span) / / console print: / / [MutationRecord]
The addedNodes attribute in MutationRecord records the additional nodes.
Remove the node:
Hello let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); / / get div let box = document.getElementById ("box"); observer.observe (box, {/ / observe the child node changes childList: true,}); / / remove the first child node, which is the Hello text node box.removeChild (box.childNodes [0]) / / console print: / / [MutationRecord]
The removedNodes attribute in MutationRecord records the removed nodes.
Move the node:
If you move an existing node, two MutationRecord records will be recorded, because moving the existing node is deleted first and then added.
Helloworld let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); / / get div let box = document.getElementById ("box"); observer.observe (box, {/ / observe the child node changes childList: true,}); / / move the span node to the front of the Hello node box.insertBefore (box.childNodes [1], box.childNodes [0]) / / when a node is moved, it is actually deleted before it is added. / / console print: / / (2) [MutationRecord, MutationRecord] 4. Observe the subtree
The nodes observed above are all the currently set target nodes, such as body, so you can only observe the changes of the body element and its child nodes.
If you want to observe the changes of body and all its descendant nodes, you can set the subtree property to true.
Helloworld let observer = new MutationObserver ((mutationRecords) = > console.log (mutationRecords)); let box = document.getElementById ("box"); observer.observe (box, {attributes: true, / / observe changes in the subtree subtree: true}); / / changes in the id attribute of the span element can be observed box.childNodes [1] .id = "text" / / console print: / / [MutationRecord]
When subtree is set to true, not only the div element itself, but also the span element can be observed.
At this point, the study on "example analysis of MutationObServer monitoring DOM elements in JavaScript" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.