开发者

jquery find previous based on class name

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>开发者_C百科

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. :/


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>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜