Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous element in the DOM?

Lets say I've got something like this:

<div class='item'>some code</div>
<div class='item current'>some code</div>
<div class='item'>some code</div>

The next element I can get by document.querySelector(".item.current + .item"). That's great and works fine but.. How can I get to the previous element?

like image 684
Xaoo Avatar asked Sep 03 '25 03:09

Xaoo


1 Answers

You can get the previous element "sibling" with the previousElementSibling property. For example

document.querySelector('.item.current').previousElementSibling

Would return the first element, <div class="item"></div>

like image 151
hackerrdave Avatar answered Sep 04 '25 16:09

hackerrdave