tags:

views:

451

answers:

2

Hey, 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). So I need target the single one.

Would really appreciate any tips :)

+5  A: 

Try:

$('li.current_sub').prevAll("li.par_cat:first");

Tested it with your markup:

$('li.current_sub').prevAll("li.par_cat:first").text("woohoo");

will fill up the closest previous li.par_cat with "woohoo".

karim79
thank you Karim. This worked well too, but I assume the .prev() would eat less resources, as .prevAll would get ALL the previous matched elements and then would filter the one I need. Accepting Ed's answer.
daulex
Actually, after a bit of texting, the .prev() failed in a few instances. .prevAll with :first, worked every time.Thank you.
daulex
+2  A: 

Try

$('li.current_sub').prev('.par_cat').[do stuff];

Ed Woodcock
doh, worked perfectly, that was way easier than I thought. Thank you.
daulex
No problem: we all have those moments ;)
Ed Woodcock