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②

瀏覽器相容性