Jquery select 3rd element previous in the sibling

Given a list of DIV

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div id="thisIsTheStart">5</div>
<div>6</div>

How can I select the 3rd last sibling (answer is 2) from the thisIsTheStart selector?


solution

You could combine the methods .eq() and .prevAll().

$('#thisIsTheStart').prevAll().eq(2)

Since the .eq() method’s index is zero-based, you would use .eq(2), which is 3.

$('#thisIsTheStart').prevAll().eq(2).css('color', '#f00');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div id="thisIsTheStart">5</div>
<div>6</div>