jQuery selector to apply a class in a list
I've a nested list, I don't know how much levels will have and I need to mark some <li />
with class="selected"
... Its better if I show you and example of my generated HTML code from PHP. I can only know one of the <li />
that will have the class.
<div id="submenu">
<ul>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li>
<a href="#">Lorem ipsum</a>
<ul>
<li>
<a href="#">Lorem ipsum</a>
<ul>
<li><a href="#">Lorem ipsum</a></li>
<li class="selected"><a hr开发者_运维百科ef="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
</ul>
</li>
<li><a href="#">Lorem ipsum</a></li>
<li>
<a href="#">Lorem ipsum</a>
<ul>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
</ul>
</li>
<li><a href="#">Lorem ipsum</a></li>
</ul>
</li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
</ul>
</div>
And what I want is add classes to the parent lists, the desired output:
<div id="submenu">
<ul>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li class="selected">
<a href="#">Lorem ipsum</a>
<ul>
<li class="selected">
<a href="#">Lorem ipsum</a>
<ul>
<li><a href="#">Lorem ipsum</a></li>
<li class="selected"><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
</ul>
</li>
<li><a href="#">Lorem ipsum</a></li>
<li>
<a href="#">Lorem ipsum</a>
<ul>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
</ul>
</li>
<li><a href="#">Lorem ipsum</a></li>
</ul>
</li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Lorem ipsum</a></li>
</ul>
</div>
Remember that is a nested list and we don't know how much levels will be.
Thank you in advance!
Do this
$('#submenu .selected').parentsUntil('#submenu').filter('li').addClass('selected');
Note: some other answers don't use parentsUntil
and will walk all the way up the DOM heirarchy. That's OK if you don't expect any other parent nodes to be li
, but I think it's safer to limit jquery to your menu.
This should do it:
$('li.selected').parents('li').addClass('selected');
Working example:
http://jsfiddle.net/Rrb9P/
The .parentsUntil()
solution is a good one.
Here's another possible way to do it:
$('#submenu li:has(.selected)').addClass('selected');
This uses the has-selector
(docs) selector to get all <li>
elements under #submenu
that have a nested selected
class.
Try this:
$("li.selected").parents("li").addClass("selected");
Why would you use jquery to do this? Couldn't you just figure out what page you were on with PHP and add the class with PHP? You would then make sure the highlight showed up even if someone had javascript turned off.
精彩评论