MutationRecord: addedNodes 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

只读属性 addedNodes 是一个 NodeList,其中包含使用 MutationObserver 观察到的突变添加到目标节点中的节点。

一个 NodeList,其中包含 MutationObserver 观察到的突变添加到目标节点中的节点。

示例

添加节点时更新

在下面的示例中,有两个按钮:一个用于向目标节点添加新节点,另一个用于删除它们。一个 MutationObserver 用于观察目标节点的更改;当检测到更改时,观察者会调用一个函数 logNewNodes()

logNewNodes() 函数会检查 MutationRecord 的 type 是否为 childList,这意味着目标节点的子节点已更改。如果类型是 childlist,该函数会更新已添加的新节点的总数。但是请注意,点击“删除节点”按钮不会增加新节点的总数,因为在这种情况下 record.addedNodes 的长度将为 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 added 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 totalAddedNodes = 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 logNewNodes(records) {
  for (const record of records) {
    // Check if the childlist of the target node has been mutated
    if (record.type === "childList") {
      totalAddedNodes += record.addedNodes.length;
      // Log the number of nodes added
      counter.textContent = `Total added nodes: ${totalAddedNodes}`;
    }
  }
}

const observer = new MutationObserver(logNewNodes);
observer.observe(target, { childList: true });

结果

规范

规范
DOM
# ref-for-dom-mutationrecord-addednodes②

浏览器兼容性