MutationRecord: nextSibling 属性

Baseline 已广泛支持

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

MutationRecord 的只读属性 nextSiblingMutationObservertarget 的添加或移除的子节点的下一个同级节点。

如果一个节点被添加到 MutationObservertarget 中,或者从其中移除,那么该属性的值就是添加或移除的节点的下一个同级节点:也就是说,在父节点的 childNodes 列表中紧随该节点之后的那个节点。

如果没有添加或移除节点,或者该节点是其父节点的最后一个子节点,则该值为 null

示例

记录突变的下一个同级节点

每次单击按钮时,此示例都会添加一个节点,但节点会添加到目标节点的开头,而不是结尾。然后,观察者会记录添加的节点的 nextSiblingtextContent

HTML

html
<button id="add-nodes">Add a node</button>
<button id="reset">Reset</button>

<pre id="log" class="log">Next sibling of added node:</pre>
<div id="target"><p>Node #0</p></div>

JavaScript

js
const addNodes = document.querySelector("#add-nodes");
const reset = document.querySelector("#reset");
const target = document.querySelector("#target");
let nodeNumber = 1;

addNodes.addEventListener("click", () => {
  const newPara = document.createElement("p");
  newPara.textContent = `Node #${nodeNumber}`;
  nodeNumber++;
  target.insertBefore(newPara, target.firstChild);
});

reset.addEventListener("click", () => self.location.reload());

function logNextSibling(records) {
  for (const record of records) {
    if (record.type === "childList") {
      for (const newNode of record.addedNodes) {
        log.textContent = `Next sibling of added node: ${record.nextSibling?.textContent}`;
      }
    }
  }
}

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

结果

规范

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

浏览器兼容性