The MutationRecord read-only property nextSibling is the next sibling of an added or removed child node of the target of a MutationObserver.
The MutationRecord read-only property nextSibling is the next sibling of an added or removed child node of the target of a MutationObserver.
If a node is added to or removed from the target of a MutationObserver, the value is the Node that is the next sibling of the added or removed node: that is, the node immediately following this one in the parent's childNodes list.
The value is null if there are no added or removed nodes, or if the node is the last child of its parent.
This adds a node every time you click the button, but it adds the node at the start of the target, not the end. Then the observer logs the textContent of the nextSibling of the added node.
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>
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.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 });
| Specification |
|---|
| DOM Standard # ref-for-dom-mutationrecord-nextsibling② |
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
nextSibling |
16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord/nextSibling