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&开发者_StackOverflowgt;
    </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?
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.
You can do that with this syntax.
$('.selected').parent().parent().addClass('foo').removeClass('bar');
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');
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论