当前位置:网站首页>Mutationobserver listens for DOM changes
Mutationobserver listens for DOM changes
2022-06-25 14:24:00 【Fat goose 68】
List of articles
One 、 Reference resources
Two 、 Quick start
// Get the element to be observed
var elementToObserve = document.querySelector("#targetElementId");
// Create a name `observer` The new `MutationObserver` example ,
// And pass the callback function to it
var observer = new MutationObserver(function() {
console.log('callback that runs when observer is triggered');
});
// stay MutationObserver Call on instance `observe` Method ,
// And pass the elements and options to be observed to this method
observer.observe(elementToObserve, {
subtree: true, childList: true});
3、 ... and 、MutationObserver Related objects and methods
3.1 MutationObserver
Reference resources MutationObserver MDN
function
MutationObserver Interface provides monitoring pairs DOM Tree's ability to make changes.Constructors MutationObserver.observe()
grammar
var observer = new MutationObserver(callback);Parameters
- callback
A callback function , Whenever the specified node or subtree and configuration item have Dom Will change when called . The callback function has two parameters : One is to describe all triggered changes MutationRecord An array of objects , The other is to call the function MutationObserver object
- callback
3.2 MutationObserver.observe()
Reference resources MutationObserver observe() MDN
grammar
mutationObserver.observe(target[, options])Parameters (MutationObserverInit object )
- target
DOM One of the trees wants to observe the changes DOM Node ( It could be a Element) , Or the root node of the observed child node tree . - options Optional
An optional one MutationObserverInit object , The configuration item of this object describes DOM What changes should be provided to the current observer callback.
- target
3.3 MutationObserverInit
Reference resources MutationObserverInit MDN
effect
MutationObserverInit The dictionary describes MutationObserver Configuration of .attribute
- attributeFilter Optional
An array of specific property names to monitor . If this property is not included , Changes to all properties will trigger a change notification . No default . - attributeOldValue (en-US) Optional
When the properties of the monitoring node are changed , Set this property to true The last value of any changed property will be recorded. For more information about observing attribute changes and value records , See Monitoring attribute values in MutationObserver. No default . - attributes (en-US) Optional
Set to true To observe the change of attribute value of the monitored element . The default value is false. - characterData (en-US) Optional
Set to true To monitor the change of character data contained in the specified target node or child node tree . No default . - characterDataOldValue (en-US) Optional
Set to true To record the previous value of the node text when the text changes on the monitored node. Details and examples , Please check out Monitoring text content changes in MutationObserver. No default . - childList Optional
Set to true To monitor the target node ( If subtree by true, Include descendant nodes ) Add or delete new child nodes . The default value is false. - subtree (en-US) Optional
Set to true To extend the monitoring range to all nodes in the whole node tree of the target node .MutationObserverInit Other values of will also apply to all nodes under this subtree , Not just on the target node . The default value is false.
- attributeFilter Optional
matters needing attention
When calling observe() When the method is used ,childList,attributes perhaps characterData Of the three properties , At least one must be true, Otherwise it will throw TypeError abnormal .
Four 、 Classic case
4.1 MutationObserver Of callback The callback function is asynchronous , Only in all DOM Only after the operation is completed will callback.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="target" class="block" name="target">
target The first child node of
<p>
<span>target The offspring of </span>
<div>
MutationObserver Of callback The callback function is asynchronous , Only in all DOM Only after the operation is completed will callback.
</div>
</p>
</div>
</body>
<script> window.onload = function () {
// Monitor for changes DOM node var target = document.getElementById("target"); var i = 0; // Node change Triggered callback function var observe = new MutationObserver(function (mutations, observe) {
i++; console.log(mutations) // Array(3) [ MutationRecord, MutationRecord, MutationRecord ] mutations.forEach((mutation) => {
// MutationRecord // {
// type: "childList", // target: div#target.block, // addedNodes: NodeList( 1 ), // removedNodes: NodeList [], // previousSibling: #text, // nextSibling: null, // attributeName: null, // attributeNamespace: null, // oldValue: null // } console.log(mutation) switch(mutation.type) {
case 'childList': /* Add or remove one or more child nodes from the tree ; See mutation.addedNodes And mutation.removedNodes */ break; case 'attributes': /* mutation.target An attribute value of a node in is changed ; The attribute name is in mutation.attributeName in , The previous value of this attribute is mutation.oldValue */ break; } }); console.log(' Start execution ', i); //1x }); observe.observe(target, {
childList: true }); target.appendChild(document.createTextNode("1")); target.appendChild(document.createTextNode("2")); target.appendChild(document.createTextNode("3")); console.log(i); //0 }; </script>
</html>
4.2 How to simulate adding nodes ?
Open the developer console , Find the one that needs to be monitored DOM node , You can add nodes 、 Delete 、 Change ( attribute ), You can start the monitoring method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<ul id="ul" class="aaa bbb">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</body>
<script> window.onload = function () {
let targetNode = document.querySelector("#ul"); let config = {
childList: true, // Observe the changes of the target child nodes , Whether to add or delete attributes: true, // Observe attribute changes attributeOldValue:true, // When the properties of the monitoring node are changed , Set this property to true The last value of any changed property will be recorded . For more information about observing attribute changes and value records subtree: true, // Observe the descendant node , The default is false characterData: true, // Monitor the change of character data contained in the specified target node or child node tree , No default }; function callback(mutationList, observer) {
mutationList.forEach((mutation) => {
console.log(mutation) debugger switch (mutation.type) {
case "childList": /* Add or remove one or more child nodes from the tree ; See mutation.addedNodes And mutation.removedNodes */ if (mutation.removedNodes.length > 0) {
console.log(' Delete node ', mutation.removedNodes) } if (mutation.addedNodes.length > 0) {
console.log(' Add a node ', mutation.addedNodes) } break; case "attributes": /* mutation.target An attribute value of a node in is changed ; The attribute name is in mutation.attributeName in , The previous value of this attribute is mutation.oldValue */ console.log(' The attribute of change is ', mutationattributeName) break; } }); } let observer = new MutationObserver(callback); observer.observe(targetNode, config); }; </script>
</html>
边栏推荐
- BACnet gateway bl103 for building automation
- Getting started with shell variables
- Golang project dependency management tool go vendor, go Mod
- 当了六年程序员第一次搞懂微服务架构的数据一致性,真不容易
- New good friend Pinia, leading the new era of state management
- Shell array
- Classifier and cross entropy loss function
- Logistic Regression VS Linear Regression
- Experts' suggestions | 8 measures to accelerate your innovative career planning and growth
- 第一次读 “Clean” 系列,并没有觉得这是一本多好的书
猜你喜欢

Haven't you understood the microservice data architecture transaction management +acid+ consistency +cap+base theory? After reading it, you can completely solve your doubts

oracle数据库常用的函数总结

Experts' suggestions | 8 measures to accelerate your innovative career planning and growth

测一测你的挣钱能力有多强?未来的你将从事什么职业?

JGG | 河北大学杜会龙组综述植物泛基因组学研究

Logistic Regression VS Linear Regression

Reading the "clean" series for the first time, I didn't think it was a good book

Sigmoid function sigmoid derivation

对白:推荐系统快速入门路线及各知识点总结

JS floating point multiplication and division method can not accurately calculate the problem
随机推荐
VGA display of de2-115 FPGA development board
Solving error: creating window glfw error: glew initialization error: missing GL version
Where is it safe to open an account for buying funds? Ask for guidance
JS floating point multiplication and division method can not accurately calculate the problem
Laravel8 implementation of picture verification code
Shell string variable
Explain the possible memory leaks caused by the handler at one time and the solutions | the developer said · dtalk
当了六年程序员第一次搞懂微服务架构的数据一致性,真不容易
One time summary: 64 common terms for data analysis!
腾讯云搭建Socks5多IP代理服务器实现游戏单窗口单IP完美搭建教程附带工具「建议收藏」
Is it safe for Guosen Securities to open a stock account? Excuse me?
通达信股票账户开户安全吗
Shell array
Variables, scopes, and variable promotion
Les neuf caractéristiques de la parole et les neuf temps en anglais
使用调试工具调试博图TCP连接所遇到的问题
Haven't you understood the microservice data architecture transaction management +acid+ consistency +cap+base theory? After reading it, you can completely solve your doubts
两种方法实现pycharm中代码回滚到指定版本(附带截图展示)
Encapsulating functions and event handling
shell 字符串变量