views:

183

answers:

3

I have a nested menu like this:

<ul id="menu">
    <li>Home
        <ul>
            <li>New</li>
            <li class="selected">Open</li>
            <li>Folder</li>
        </ul>
    </li>
    <li>Another menu
        <ul>
            <li>submenu item 1</li>
            <li>submenu item 2</li>
            <li>submenu item 3</li>
        </ul>
    </li>
</ul>

Now I'm trying to change the class of the first LI element (the one that contains Home), because it has a child element with a "selected" class. Is this possible using jQuery?

+1  A: 

You can do that with this syntax.

$('.selected').parent().parent().addClass('foo').removeClass('bar');
Niels Bom
Better to use .parents() selector
Nimbuz
I don't see how it would be better exactly, could you give an example?
Niels Bom
+3  A: 

A faster and more precise method in catching targets.

$("li.selected").parents("#menu").addClass('foo');

Updated to add some class to first li child.

$("li.selected").parents("#menu").addClass('foo').find('li:first').addClass('bar');

I also reccomend reading the jQuery Traversing documentation.

Elzo Valugi
I'd like to add a CSS class to <li>Home. How should I do that?
jao
This won't work if you have any `<li>`'s selected inside "Another menu"
fudgey
the response is based on given HTML code.
Elzo Valugi
A: 

Try

$('li.selected').parent().closest('li').addClass('foo');

Edit: Sorry, only using closest will make it target itself.

or you can use:

$('li.selected').closest('li:not(".selected")').addClass('foo');
fudgey