当前位置:网站首页>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>
边栏推荐
- 阻止深度神经网络过拟合(Mysteries of Neural Networks Part II)
- shell 内置命令
- JS component
- 超酷汇编教程-- 简明x86汇编语言教程(1)
- Discriminative v.s.Generative
- oracle数据库常用的函数总结
- Realization of neural networks with numpy
- Output 0 ~ n digits and output multiple times
- How to choose a technology stack for web applications in 2022
- Does stream even have application advanced learning? As a programmer, you know what
猜你喜欢

What are the red lines of open source that should not be trodden on?

Shell string variable
![[untitled] the CMD command window displays' NPM 'which is not an internal or external command](/img/db/b1ae4b0d1110af1e24887ba3b4fe16.jpg)
[untitled] the CMD command window displays' NPM 'which is not an internal or external command

Nr-arfcn and channel grid, synchronous grid and GSCN

To make pytorch faster, you need to master these 17 methods

Preventing overfitting of deep neural networks (mysteries of neural networks Part II)

电脑必须打开的设置

权益NFT开创者Hash Eagle如何重新定义NFT,用权益赋能长续价值?

使用调试工具调试博图TCP连接所遇到的问题

New good friend Pinia, leading the new era of state management
随机推荐
Summary of common functions in Oracle Database
广发易淘金和同花顺哪个更好,更安全一些
‘nvidia-smi‘ 不是内部或外部命令,也不是可运行的程序或批处理文件
Share the code technology points and software usage of socket multi client communication
The best screenshot tool in the world, color absorption tool snipaste
电脑必须打开的设置
买基金在哪里开户安全?求指导
腾讯云搭建Socks5多IP代理服务器实现游戏单窗口单IP完美搭建教程附带工具「建议收藏」
laravel8实现图片验证码
Hash table, hash conflict
Let and const commands
【世界历史】第二集——文明的曙光
英語中的九大詞性與九大時態
对白:推荐系统快速入门路线及各知识点总结
Complete and detailed compilation of experimental reports
Turtlebot+lms111+gmapping practice
深入理解深度神经网络背后的数学(Mysteries of Neural Networks Part I)
As a software testing engineer, how do you think to ensure software quality?
What is the safest app for stock account opening? Tell me what you know
分享自己平時使用的socket多客戶端通信的代碼技術點和軟件使用