监听页面上的 DOM 树变化
记录一下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div id="hello">hello word!</div>
<script>
var targetNode = document.querySelector("body");
// subtree:是否监听子节点的变化
var config = { attributes: true, childList: true, subtree: true };
var callback = function(mutationsList) {
// Dom发生变化,加载时也会生效
for (var mutation of mutationsList) {
console.log(mutation)
if (mutation.type == "childList") {
console.log("有一个子节点被添加或移除")
} else if (mutation.type == "attributes") {
console.log('这个' + mutation.attributeName + '属性被修改')
}
}
};
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);
setTimeout(() => {
var divnode = document.createElement("div");
divnode.id = 'word'
var textNode = document.createTextNode("word");
divnode.appendChild(textNode);
document.getElementById("hello").appendChild(divnode);
},2000)
</script>
</body>
</html>