当前位置:网站首页>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>
边栏推荐
- Tencent cloud builds a Socks5 multi IP proxy server to realize the perfect building of a game with a single window and a single IP. Tutorial attached tool "suggestions collection"
- 当了六年程序员第一次搞懂微服务架构的数据一致性,真不容易
- 【世界历史】第一集——石器时代的人们
- K-line diagram 24 classic diagrams (shadow)
- Supplementary inheritance and strict mode
- Clinical Chemistry | 张建中/徐健开发幽门螺杆菌单细胞精准诊疗技术
- None of the MLIR Optimization Passes are enabled (registered 2)解决办法
- 程序員為什麼要軟一點?
- Custom instruction, mixing, routing, lifecycle
- Shell string variable
猜你喜欢
程序员为什么要软一点?
专家建议|8大措施加速你的创新职业规划和成长
Sigmoid function sigmoid derivation
Classifier and cross entropy loss function
Deeply understand the mathematics behind deep neural networks (mysteries of neural networks Part I)
Shell operator
'NVIDIA SMI' is not an internal or external command, nor is it a runnable program or batch file
China has made major breakthroughs in battery technology. Japan, South Korea and the United States are lagging behind. China has consolidated its leading edge
How does hash eagle, the founder of equity NFT, redefine NFT and use equity to enable long-term value?
Kubernetes cluster construction of multiple ECS
随机推荐
Shell built-in commands
Hash table, hash conflict
深入理解深度神经网络背后的数学(Mysteries of Neural Networks Part I)
‘nvidia-smi‘ 不是内部或外部命令,也不是可运行的程序或批处理文件
The best screenshot tool in the world, color absorption tool snipaste
PubSub JS library realizes "cross component" data transfer
Summary of common functions in Oracle Database
Table de hachage, conflit de hachage
TSDB在民机行业中的应用
Shell array
New good friend Pinia, leading the new era of state management
一次性总结:64个数据分析常用术语!
Suanli & NFT trading platform f3 The exclusive NFT project of XYZ, hash eagle, will be grandly launched
Asp.net WebForm使用NPOI导出Excel
Laravel8 implementation of picture verification code
Custom instruction, mixing, routing, lifecycle
Does stream even have application advanced learning? As a programmer, you know what
分享自己平时使用的socket多客户端通信的代码技术点和软件使用
Partager les points techniques de code et l'utilisation de logiciels pour la communication Multi - clients socket que vous utilisez habituellement
K-line diagram 24 classic diagrams (shadow)