MutationRecord: previousSibling 属性

Baseline 已广泛支持

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

MutationRecord 只读属性 previousSiblingMutationObservertarget 的子节点添加或删除时的前一个同级节点。

如果一个节点被添加到 MutationObservertarget 中或从中被移除,则该值为添加或移除节点的 Node,即父节点的 childNodes 列表中该节点前面的那个节点。

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

示例

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

每次点击按钮时,都会添加一个节点。然后观察者会记录新添加节点的 previousSiblingtextContent

HTML

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

<pre id="log" class="log">Previous 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.appendChild(newPara);
});

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

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

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

结果

规范

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

浏览器兼容性