Get the Previous Element with JavaScript previousElementSibling

01/03/2022
Contents
In this article, you will learn 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;
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>