JavaScript previousElementSibling Property Tutorial

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

What is Element previousElementSibling Property in JavaScript?

The JavaScript Element `previousElementSibling` property is used to get a reference to the previous 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 `previousElementSibling` property on the last item will return the second item that has the value “Item 2”.

Note that we’re saying the previous `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 move on until it reaches a previous sibling that is of type Element-node.

JavaScript previousElementSibling Property Syntax:

element.previousElementSibling;

JavaScript previousElementSibling Property Input Value

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

JavaScript previousElementSibling Property Return Value

The return value of this property, as mentioned before, is the previous `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 previousElementSibling Property in JavaScript

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

How does the previousElementSibling 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 `previousElementSibling` property on the last item, you can see the `text-node` between the two items is ignored and the first <li> element returned as a result.

Again, this is because the previousElementSibling property looks for the previous sibling of the node that is an `Element-node`.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies