nextsibling vs nextelementsibling

NextSibling vs NextElementSibling

As a web developer, I have often come across the terms nextSibling and nextElementSibling while working with JavaScript. Both of these properties are used to navigate to the next sibling element of a given element in the DOM tree. However, there is a major difference between them.

The nextSibling Property

The nextSibling property returns the next sibling node (including text nodes) of the current element in the DOM tree. Let me give you an example:


// HTML code
<div id="parent">
    <p>First child</p>
    <span>Second child</span>
    <ul>
        <li>Third child</li>
        <li>Fourth child</li>
    </ul>
</div>

// JavaScript code
let secondChild = document.getElementById('parent').firstChild.nextSibling;
console.log(secondChild); // Output: #text

let thirdChild = secondChild.nextSibling.nextSibling;
console.log(thirdChild); // Output: <ul>...</ul>

In the above example, the nextSibling property is used to navigate from the first child element to the second child element, which is a text node. Then, it is used again to navigate to the third child element, which is an unordered list (<ul>) node.

The nextElementSibling Property

The nextElementSibling property, on the other hand, returns the next sibling element node (excluding text nodes) of the current element in the DOM tree. Here's an example:


// HTML code
<div id="parent">
    <p>First child</p>
    <span>Second child</span>
    <ul>
        <li>Third child</li>
        <li>Fourth child</li>
    </ul>
</div>

// JavaScript code
let secondChild = document.getElementById('parent').firstElementChild.nextElementSibling;
console.log(secondChild); // Output: <span>...</span>

let thirdChild = secondChild.nextElementSibling;
console.log(thirdChild); // Output: <ul>...</ul>

In the above example, the nextElementSibling property is used to navigate from the first child element to the second child element, which is a <span> node. Then, it is used again to navigate to the third child element, which is an <ul> node.

It is important to note that if there are no more element nodes after the current element, both properties will return null.

In summary, while nextSibling returns any type of node (including text nodes), nextElementSibling returns only element nodes. Therefore, it is recommended to use nextElementSibling when you want to navigate to the next element node in the DOM tree.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe