HTML DOM nextSibling Property Examples
Example: In this example, we will use the DOM nextSibling property to retrieve the inner HTML content of the sibling element after the element with id “p1” and updates the paragraph element accordingly.
<!DOCTYPE html>
<html>
<head>
<title>DOM nextSibling Property</title>
</head>
<body>
<h2>DOM nextSibling Property</h2>
<div>
<span id="p1"> w3wiki! </span
><span id="p2">
A computer science portal for
geeks.
</span>
</div>
<br />
<button onclick="geek()">
Click me!
</button>
<br />
<br />
<p id="p"></p>
<script>
function geek() {
let x =
document.getElementById("p1")
.nextSibling.innerHTML;
document.getElementById(
"p"
).innerHTML = x;
document.getElementById(
"p"
).style.color = "white";
document.getElementById(
"p"
).style.background = "green";
}
</script>
</body>
</html>
Output:
Note: Don’t put whitespace between two sibling elements, else the result will be “undefined”.
HTML DOM nextSibling Property
The nextSibling property returns the next node at the same tree level, providing a node object. It’s read-only and navigates through sibling nodes within the document structure.
Syntax:
node.nextSibling
Return value:
Name | Description |
---|---|
Node | The nextSibling property returns the next sibling node or null if none exists. |
Note: next sibling node: element, text, or comment node; includes whitespace as text nodes between elements.