4

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
  • 167
  • 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

8

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
  • 6,486
  • 1
  • 25
  • 29
4
document.querySelector(".item.current").previousElementSibling
dippas
  • 58,591
  • 15
  • 114
  • 126
Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
0

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

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
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,595
  • 3
  • 39
  • 55