I am trying to add a class of 'active' to a parent list item if one of it's children has the class 'active'.
Current html:
<ul class="top">
<li class="parent"><a href="#">Link1</a>
<ul class="drop">
<li class="active"><a href="#">Link1-1</a></li>
<li><a href="#">Link1-2</a></li>
<li><a href="#">Link1-3</a></li>
</ul>
</li>
<li><a href="#">Link2</a></li>
<li class="parent"><a href="#">Link3</a></li>
</ul>
current JQuery:
if($('ul.top li ul.drop li').hasClass('active')) {
$('ul.top li.parent').addClass('active');
}
Please see http://jsfiddle.net/FmT52/ to view how far I have got.
I have managed to half do it but only so far as using Jquery to add the class of 'active' to all top level list items.
As ever, any help will be greatly appreciated.
You can loop over all the li's and add the class to the closest parent ul
$('ul.top li').each(function(){
var $this = $(this);
if($this.hasClass('active')){
$this.closest('li.parent').addClass('active');
}
});
Check fiddle
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