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② |
浏览器兼容性
加载中…