大网数据广告活动
Web 标准与前端开发

MutationRecord: nextSibling property

· 52CE 我爱测

The MutationRecord read-only property **`nextSibling`** is the next sibling of an added or removed child node of the `target` of a MutationObserver.

DOM

The MutationRecord read-only property nextSibling is the next sibling of an added or removed child node of the target of a MutationObserver.

Value

If a node is added to or removed from the target of a MutationObserver, the value is the Node that is the next sibling of the added or removed node: that is, the node immediately following this one in the parent's Node.childNodes list.

The value is null if there are no added or removed nodes, or if the node is the last child of its parent.

Examples

Log the next sibling of a mutation

This adds/removes a node every time you click the button, but it performs the update at the start of the target, not the end. Then the observer logs the textContent of the nextSibling of the updated node.

HTML

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

<pre id="log" class="log">Next sibling of updated node:</pre>
<div id="target"><p>Node #0</p></div>
.log {
  border: 1px dotted black;
  padding: 0.5rem;
}

JavaScript

const addNodes = document.querySelector("#add-nodes");
const removeNodes = document.querySelector("#remove-nodes");
const reset = document.querySelector("#reset");
const target = document.querySelector("#target");

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

removeNodes.addEventListener("click", () => {
  const oldPara = target.firstChild;
  if (oldPara) {
    target.removeChild(oldPara);
  }
});

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

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

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

Result

Log the next sibling of a mutation

Specifications

Browser compatibility

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。