MutationRecord: previousSibling 屬性
MutationRecord 只讀屬性 previousSibling 是 MutationObserver 的 target 的子節點新增或刪除時的前一個同級節點。
值
如果一個節點被新增到 MutationObserver 的 target 中或從中被移除,則該值為新增或移除節點的 Node,即父節點的 childNodes 列表中該節點前面的那個節點。
如果沒有新增或移除節點,或者該節點是其父節點的第一個子節點,則值為 null。
示例
記錄突變的前一個同級節點
每次點選按鈕時,都會新增一個節點。然後觀察者會記錄新新增節點的 previousSibling 的 textContent。
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② |
瀏覽器相容性
載入中…