tags:

views:

32

answers:

1

Hi all, I'm trying to use jquery to find an item based on it's class name. Basically I have this structure:

<ul class="vm_cat">
    <li><a class="mainlevel" href="/">MAIN LEVEL 1</a></li>
    <li><a class="sublevel" href="/">sub 1 a</a></li>
    <li><a class="sublevel" href="/">sub 1 b</a></li>
    <li><a class="sublevel" href="/">sub 1 c</a></li>
    <li><a class="sublevel" href="/">sub 1 d</a></li>
    <li><a class="mainlevel" href="">MAIN LEVEL 2</a></li>
    <li><a class="sublevel" href="/">sub 2 a</a></li>
    <li><a class="sublevel" href="/" id="active">sub 2 b</a></li>
    <li><a class="sublevel" href="/">sub 2 c</a></li>
    <li><a class="mainlevel" href="/">MAIN LEVEL 3</a></li>
    <li><a class="sublevel" href="/">sub 3 a</a></li>
</ul>

I want jQuery to find which a tag has an id of "active", then to find the previous a tag with "mainlevel". So it would find "sub 2 b" and then find "MAIN LEVEL 2" as it is the previous a tag with a class of "mainlevel".. if this makes any sense??

I know this would be a lot easier if the list was structured correctly, but this is what I have to work with unfortunately. :/

+4  A: 

You can do it using .prevAll() and :first, like this:

$("#active").parent().prevAll(":has(.mainlevel):first")​.children()

Give it a try here

This goes up to the parent, then searches all previous siblings that contain the provided selector (using :has()), and they're in reverse order (nearest sibling first), so you want the :first one, then go to the child to get the <a> inside the <li>.

Nick Craver
+1 - Yep, the `:has()` capped it off. Don't know what I was thinking! :o)
patrick dw
thank you muchly :)
SoulieBaby
is there any way of hiding the sub level items, belonging to a mainlevel "group" which doesn't have an item with "active" as the id?
SoulieBaby
@SoulieBaby: Is there any reason for the main levels not being a `<li>` set of siblings, each with a `<ul>` underneath, containing `<li>` elements that are the `.sublevel` ones? This would simplify everything greatly.
Nick Craver
I'm trying to modify an already structured system, I don't have access to the specific files to re-do that list :S I can only modify certain pages *sigh*
SoulieBaby
@SoulieBaby - You can do it like this: http://jsfiddle.net/nick_craver/xUhCm/
Nick Craver
thanks nick, will check it out :)
SoulieBaby