简体   繁体   中英

Get <li> with child <ul> from <ul> child of <li>

I have a very simple example of a menu here:

<ul id="1">
    <li><a href="#">First</a></li>
    <li><a href="#">Second</a>
    <ul id="2">
        <li><a href="#">Second - 1</a></li>
        <li><a href="#">Second - 2</a></li>
        <li><a href="#">Second - 3</a>
        <ul id="3">
            <li><a href="#">Aaa</a></li>
            <li><a href="#">Bbb</a></li>
            <li><a href="#">Ccc</a></li>
        </ul>
        </li>
    </ul>
    </li>
    <li><a href="#">Third</a></li>
</ul>

I need to get the <li> that has a child <ul> and that is a child of <ul> who is a child of <li> , and apply a style to it.

I know it sounds complicated, but in the example above I want to get only the <li> that says "Second - 3" which is inside a ul, which is a child of a li and has a child ul. I don't want to get any other <li> s.

I can't do this without getting also the li which says "Second", and I don't want that.

$("li > ul").addClass('whatever');

Use $("li ul li:has(ul)")

eg:

$(function(){
    var items = $("li ul li:has(ul)");
    alert(items.html());
});

Working example: http://jsfiddle.net/EXzaa/

Try this:

$("li > ul > li").each(function(){
    if ( $(this).find("ul").length > 0){
        $(this).css({"font-weight":"bold"});
    }
});

Unless I get you wrong this is simple. Try something like this:

$('#3').parent('li').addClass('whatever');

This will select the parent node of the ul element with the id = 3 (only if it is an li element)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM