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&开发者_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');
精彩评论