jQuery find closest previous sibling with class
Here's the rough HTML I get to work with:
<li class="par_cat"></li>
<li class="sub_cat"></li>
<li class="sub_cat"></li>
<li class="par_cat"></li> // this is the single element I need to select
<li class="sub_cat"></li>
<li class="sub_cat"></li>
<li class="sub_cat current_sub"></li> // this is where I need to start searching
<li class="par_cat"></li>
<li class="sub_cat"></li>
<li class="par_cat"></li>
I need to traverse from the .current_sub
, find the closest previous .par_cat
and do stuff to it.
.find("li.par_cat")
returns the whole load of .par_cat
(I've got about 30 on the page). I need target the single one.
Try:
$('li.current_sub').prevAll("li.par_cat:first");
Tested it with your markup:
$('li.current_sub').prevAll("li.par_cat:first").text("woohoo");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="par_cat"></li>
<li class="sub_cat"></li>
<li class="sub_cat"></li>
<li class="par_cat">// this is the single element I need to select</li>
<li class="sub_cat"></li>
<li class="sub_cat"></li>
<li class="sub_cat current_sub">// this is where I need to start searching</li>
<li class="par_cat"></li>
<li class="sub_cat"></li>
<li class="par_cat"></li>
</ul>
will fill up the closest previous li.par_cat
with "woohoo".
Try
$('li.current_sub').prev('.par_cat').[do stuff];
Using prevUntil() will allow us to get a distant sibling without having to get all. I had a particularly long set that was too CPU intensive using prevAll().
var category = $('li.current_sub').prev('li.par_cat');
if (category.length == 0){
category = $('li.current_sub').prevUntil('li.par_cat').last().prev();
}
category.show();
This gets the first preceding sibling if it matches, otherwise it gets the sibling preceding the one that matches, so we just back up one more with prev() to get the desired element.
I think all the answers are lacking something. I prefer using something like this
$('li.current_sub').prevUntil("li.par_cat").prev();
Saves you not adding :first inside the selector and is easier to read and understand. prevUntil() method has a better performance as well rather than using prevAll()