Get the Previous Element with JavaScript previousElementSibling | Plantpot

Get the Previous Element with JavaScript previousElementSibling

Web Dev
Sponsored links

In this article, I will introduce how to get the previous element with JavaScript previousElementSibling.

What is previousElementSibling?

The previousElementSibling is a property that gets the previous element of the specified Element object.
You can get sibling elements with the same parent element except text node and comment node by previousElementSibling.
If the previous element does not exist, it returns "null".

The syntax is as follows.

let element = document.getElementById('element');

element.previousElementSibling; 
Sponsored links

Get the previous element with previousElementSibling

Get the previous element adjacent by specifying the element with a specific id.

HTML

<ul>
  <li></li>
  <li id="target"></li>
</ul>

JavaScript

let element = document.getElementById('target');
element.previousElementSibling;

//result
//<li>