Is there a way to make the selector below better?
Without adding extra classes or id’s?
Only select the first item-2 counted from item-5 downwards.
This works, but there has to be an easier way.
$first_previous = $($('li.item-5').prevAll('.item-2')[0]);
<ul>
<li class="item-1">list item 1</li>
<li class="item-2">Unkown number of item-2 will happen</li>
<li class="item-2">Unkown number of item-2 will happen</li>
<li class="item-2">list item 2 Only select this one, not the other #2</li>
<li class="item-3">list item 3</li>
<li class="item-4">list item 4</li>
<li class="item-5">list item 5 Start here</li>
<li class="item-2">it might even occur after the item-5</li>
</ul>
You could try :
(Where
$(this)is a jQuery object containing an element with a class of.item-5)But you will want to use something like http://jsperf.com/ to find out which way is quicker !
Working example here
Update
Then try this :
Docs for
.last()OK … then try :
Uses
.prev()Update 2
Loop the items and get the first which will be the one you want :
Example here