1

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?

Xaoo
  • 137
  • 1
  • 3
  • 9
  • Here's your answer: [Is there a “previous sibling” CSS selector?](http://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-css-selector) – german meza Nov 21 '16 at 23:57

4 Answers4

4
document.querySelector(".item.current").previousElementSibling
dippas
  • 52,735
  • 15
  • 110
  • 120
Stefan Haustein
  • 17,837
  • 3
  • 33
  • 48
4

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>

hackerrdave
  • 5,946
  • 1
  • 23
  • 28
0

You can just do document.querySelector(".item.current").previousElementSibling.

Lakshya Thakur
  • 7,282
  • 1
  • 8
  • 34
0

There is no "previous sibling" selector that you can use directly.

You can use javascript to select it using document.querySelector(".item.current").previousElementSibling

Community
  • 1
  • 1
hughes
  • 5,255
  • 3
  • 33
  • 53