Cthulhu
Cthulhu

Reputation: 5235

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');

Upvotes: 0

Views: 1055

Answers (3)

Markus Ivany
Markus Ivany

Reputation: 11

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)

Upvotes: 1

Derrick
Derrick

Reputation: 2021

Try this:

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

Upvotes: 1

Chandu
Chandu

Reputation: 82893

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

e.g:

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

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

Upvotes: 6

Related Questions