MutationRecord: removedNodes 属性
MutationRecord 只读属性 removedNodes 是一个 NodeList,其中包含通过 MutationObserver 观察到的变异从目标节点中移除的节点。
值
一个 NodeList,包含由 MutationObserver 观察到的变异目标中移除的节点。
示例
观察已移除的节点
在以下示例中,有两个按钮:一个用于向目标节点添加新节点,另一个用于移除节点。使用 MutationObserver 来观察目标节点的变化;检测到变化时,观察者会调用一个函数 logRemovedNodes()。
logRemovedNodes() 函数检查 MutationRecord 的 type 是否为 childList,这意味着目标节点的子节点已发生更改。如果类型为 childlist,该函数会更新已移除节点的总数。但是请注意,点击“添加节点”按钮不会增加已移除节点的总数,因为在这种情况下 record.removedNodes 的长度将为 0。
HTML
html
<button id="add-nodes">Add a node</button>
<button id="remove-nodes">Remove a node</button>
<button id="reset">Reset</button>
<pre id="counter">Total removed nodes: 0</pre>
<div id="target"></div>
JavaScript
js
const addNodes = document.querySelector("#add-nodes");
const removeNodes = document.querySelector("#remove-nodes");
const reset = document.querySelector("#reset");
const counter = document.querySelector("#counter");
const target = document.querySelector("#target");
let totalRemovedNodes = 0;
addNodes.addEventListener("click", () => {
const newPara = document.createElement("p");
newPara.textContent = `Current time: ${Date.now()}`;
target.appendChild(newPara);
});
removeNodes.addEventListener("click", () => {
const lastChild = target.lastChild;
if (lastChild) {
target.removeChild(lastChild);
}
});
reset.addEventListener("click", () => self.location.reload());
function logRemovedNodes(records) {
for (const record of records) {
// Check if the childlist of the target node has been mutated
if (record.type === "childList") {
totalRemovedNodes += record.removedNodes.length;
// Log the number of nodes added
counter.textContent = `Total removed nodes: ${totalRemovedNodes}`;
}
}
}
const observer = new MutationObserver(logRemovedNodes);
observer.observe(target, { childList: true });
结果
规范
| 规范 |
|---|
| DOM # ref-for-dom-mutationrecord-removednodes② |
浏览器兼容性
加载中…