Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent of a child element that has a certain class

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?

like image 985
jao Avatar asked Dec 30 '22 11:12

jao


2 Answers

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.

like image 97
Elzo Valugi Avatar answered Jan 13 '23 13:01

Elzo Valugi


You can do that with this syntax.

$('.selected').parent().parent().addClass('foo').removeClass('bar');
like image 37
Niels Bom Avatar answered Jan 13 '23 14:01

Niels Bom