JavaScript nextElementSibling Property Tutorial

In this section, we will learn what the Element nextElementSibling property is and how to use it in JavaScript.

What is Element nextElementSibling Property in JavaScript?

The JavaScript Element `nextElementSibling` property is used to get a reference to the next Element-node sibling of the current node (the one that invoked this property).

For example, if you have a list with three <li> elements with the values “Item 1” , “Item 2”, and “Item 3” set for each item respectively, then calling the `nextElementSibling` property on the first item will return the second item that has the value “Item 2”.

Note that we’re saying the next `Element-node` sibling! That means if the immediate sibling of the target node is a node of type Text or Comment for example, this property will ignore it and moves on until it reaches to the first sibling that is of type Element-node.

JavaScript nextElementSibling Property Syntax:

element.nextElementSibling;

JavaScript nextElementSibling Property Input Value

The nextElementSibling property is read-only and so we can’t assign a value to it.

JavaScript nextElementSibling Property Return Value

The return value of this property, as mentioned before, is the next `Element-node` sibling of the node (the one that invoked the property)

Note: if there’s no sibling, the return value of this property will be null.

Example: using nextElementSibling in JavaScript

See the Pen using nextElementSibling in JavaScript by Omid Dehghan (@odchan1) on CodePen.

How does the nextElementSibling property work in JavaScript?

Here in this example, there’s a text-node between the first and the second items of the list. But when we’ve called the `nextElementSibling` property on the first item, you can see the `text-node` between the two items is ignored and the second <li> element returned as a result.

Again, this is because the nextElementSibling property looks for the next sibling of the node that is of type `Element-node`.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies