MutationRecord: thuộc tính nextSibling
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Thuộc tính chỉ đọc nextSibling của MutationRecord là anh em kế tiếp của một nút con được thêm hoặc xóa tại target của một MutationObserver.
Giá trị
Nếu một nút được thêm vào hoặc xóa khỏi target của một MutationObserver, giá trị là Node đóng vai trò là anh em kế tiếp của nút được thêm hoặc xóa: tức là nút đứng ngay sau nó trong danh sách childNodes của nút cha.
Giá trị là null nếu không có nút nào được thêm hoặc xóa, hoặc nếu nút đó là phần tử con cuối cùng của nút cha.
Ví dụ
>Ghi lại anh em kế tiếp của một biến đổi
Ví dụ này thêm một nút mỗi khi bạn nhấn nút, nhưng nó chèn nút đó vào đầu của target, không phải cuối. Sau đó observer ghi lại textContent của nextSibling của nút được thêm.
HTML
<button id="add-nodes">Add a node</button>
<button id="reset">Reset</button>
<pre id="log" class="log">Next sibling of added node:</pre>
<div id="target"><p>Node #0</p></div>
JavaScript
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.insertBefore(newPara, target.firstChild);
});
reset.addEventListener("click", () => self.location.reload());
function logNextSibling(records) {
for (const record of records) {
if (record.type === "childList") {
for (const newNode of record.addedNodes) {
log.textContent = `Next sibling of added node: ${record.nextSibling?.textContent}`;
}
}
}
}
const observer = new MutationObserver(logNextSibling);
observer.observe(target, { childList: true });
Kết quả
Thông số kỹ thuật
| Thông số kỹ thuật |
|---|
| DOM> # ref-for-dom-mutationrecord-nextsibling②> |