Reputation: 1277
It should be easy, but somehow I didn't get this one yet. Hope you can help me.
Simply: I would like the parent LI to get a class "item_active" added when one of the child LIs have that class too.
<ul class="nav navbar-nav">
<li class=""><a href="main"><span>Main</span></a></li>
<li class="dropdown"><a href="services" class="dropdown-toggle" data-toggle="dropdown"><span>Services</span></a>
<ul class="dropdown-menu">
<li><a href="first"><span>First</span></a></li>
<li class="item_active"><a href="second"><span>Second</span></a></li>
<li><a href="third"><span>Third</span></a></li>
</ul>
</li>
<li><a href="about"><span>About</span></a></li>
<li><a href="contact"><span>Contact</span></a></li>
</ul>
You'll see that the second LI in the sub dropdown menu has the class "item_active".
In this scenario I want jQuery to add the class "item-active" to the LI with the class "dropdown" in my case.
I tried many different things. This is may be most close, yet it did nothing:
$('.navbar-nav li ul li').each(function(){
if($(this).hasClass('item_active')) {
$(this).closest('.dropdown').addClass('item_active');
}
});
I have read many different answers in SO, but not one that solved this.
Upvotes: 0
Views: 43
Reputation: 40459
The fiddle you provided doesn't use jQuery. Load that in and it would work.
DEMO: https://jsfiddle.net/dirtyd77/cxnx1147/6/
Also, keep in mind that bootstrap uses particular classes that override properties. Just because you can't "see" the class, doesn't mean it hasn't been added to the element.
To illustrate this, I used the following:
.item_active {
background: yellow!important;
}
It's important to note that !important
is not considered good practice though.
Hope this helps.
Upvotes: 1