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② |
瀏覽器相容性
載入中…