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?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With