In JavaScript, the nextElementSibling
property is used to access the element that comes immediately after a given element in the DOM (Document Object Model) tree. It returns the next sibling element node, excluding any non-element nodes like text nodes or comments.
Here’s an example of usage:
const element = document.getElementById('myElement');
const nextSibling = element.nextElementSibling;
In this example, myElement
is an element in the document, and nextElementSibling
is used to retrieve its immediate sibling element. The nextSibling
variable will contain the reference to the next element in the DOM structure.
If there is no next element sibling, the nextElementSibling
property will return null
. Therefore, it’s a good practice to check if the value is null
before accessing properties or calling methods on the returned element to avoid errors.
const element = document.getElementById('myElement');
const nextSibling = element.nextElementSibling;
if (nextSibling !== null) {
// Do something with the next sibling element
} else {
// There is no next sibling element
}
JavaScript nextElementSibling example
Simple example code that demonstrates the usage of the nextElementSibling
property in JavaScript:
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li id="currentItem">Item 2</li>
<li>Item 3</li>
</ul>
<script>
const currentItem = document.getElementById('currentItem');
const nextItem = currentItem.nextElementSibling;
if (nextItem !== null) {
// Add a class to the next sibling element
nextItem.classList.add('highlight');
} else {
console.log('There is no next sibling element.');
}
</script>
</body>
</html>
Output:
If there is no next sibling element, we log a message to the console indicating that there is no next sibling.
Comment if you have any doubts or suggestions on this Js DOM Property topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version