The nextElementSibling property returns the next sibling element of a specified element (or null if none exists). Unlike nextSibling (which can return text or comment nodes), it returns only element nodes and is read-only.
Syntax
node.nextElementSiblingReturn value: This property returns a next sibling of the specified element or null if the current element has no next sibling.
Example: In this example, we will use the nextElementSibling property
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
DOM nextSibling Property
</title>
</head>
<body style="text-align: center">
<h2 style="color:green;">
DOM nextElementSibling Property
</h2>
<h4 id="h42">Web Languages:</h4>
<select size="4">
<option>HTML</option>
<option id="Select">CSS</option>
<option>JAVA SCRIPT
</option>
<option>XML</option>
</select>
<br>
<br>
<!--Driver Code Ends-->
<button onclick="geek()">Next of CSS</button>
<br>
<br>
<p id="p" style="margin:auto; width: 40%"></p>
<script>
function geek() {
let a =
document.getElementById("Select").nextElementSibling;
document.getElementById("p").innerHTML = a.text;
document.getElementById("p").style.color = "white";
document.getElementById("p").style.background = "green";
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- element.nextElementSibling skips text nodes, comments, and other non-element nodes, returning only the next Element sibling (or null if none exists).
- Use nextElementSibling when you want the next element sibling (ignoring whitespace text nodes). Use nextSibling when you need the next sibling of any node type. The matching previous property is previousElementSibling.