In my menu I would like to add an active class to one of my elements: li.nav-item
and this only if the child item: ul.nav-collapse.li has the active class.
for this I made a script that works but it adds the active class to all elements: li.nav-intem
I would like it to select only the relevant parent: li.nav-item
which contains the active class ul.nav-collapse.li.active
JS
$('ul.nav-collapse li').each(function(){
if($(this).hasClass('active')) {
$(this).parent().parent().parent().parent().find('li.nav-item').addClass("active");
}
});
HTML
<ul>
<li class="nav-item">
<a class="" data-toggle="collapse" href="#submenu1">
<p>My Folder</p>
</a>
<div class="collapse" id="submenu1">
<ul class="nav nav-collapse">
<li class="">
<a href="SubFolder">
<span class="sub-item">SubFolder</span>
</a>
</li>
<li class="active">
<a href="SubFolder2">
<span class="sub-item">SubFolder2</span>
</a>
</li>
</ul>
</div>
</li>
<li class="nav-item">
<a class="" data-toggle="collapse" href="#submenu2">
<p>My Folder2</p>
</a>
<div class="collapse" id="submenu2">
<ul class="nav nav-collapse">
<li class="">
<a href="SubFolder2">
<span class="sub-item">SubFolder2</span>
</a>
</li>
<li class="">
<a href="SubFolder2_2">
<span class="sub-item">SubFolder2_2</span>
</a>
</li>
</ul>
</div>
</li>
<li class="nav-item">
<a class="" data-toggle="collapse" href="#submenu3">
<p>My Folder2</p>
</a>
<div class="collapse" id="submenu3">
<ul class="nav nav-collapse">
<li class="">
<a href="SubFolder3">
<span class="sub-item">SubFolder3</span>
</a>
</li>
<li class="">
<a href="SubFolder3_2">
<span class="sub-item">SubFolder3_2</span>
</a>
</li>
</ul>
</div>
</li>
</ul>
I would like something like this
<ul>
<li class="nav-item active">
<a class="" data-toggle="collapse" href="#submenu1">
<p>My Folder</p>
</a>
<div class="collapse" id="submenu1">
<ul class="nav nav-collapse">
<li class="">
<a href="SubFolder">
<span class="sub-item">SubFolder</span>
</a>
</li>
<li class="active">
<a href="SubFolder2">
<span class="sub-item">SubFolder2</span>
</a>
</li>
</ul>
</div>
</li>
<li class="nav-item">
<a class="" data-toggle="collapse" href="#submenu2">
<p>My Folder2</p>
</a>
<div class="collapse" id="submenu2">
<ul class="nav nav-collapse">
<li class="">
<a href="SubFolder2">
<span class="sub-item">SubFolder2</span>
</a>
</li>
<li class="">
<a href="SubFolder2_2">
<span class="sub-item">SubFolder2_2</span>
</a>
</li>
</ul>
</div>
</li>
<li class="nav-item">
<a class="" data-toggle="collapse" href="#submenu3">
<p>My Folder2</p>
</a>
<div class="collapse" id="submenu3">
<ul class="nav nav-collapse">
<li class="">
<a href="SubFolder3">
<span class="sub-item">SubFolder3</span>
</a>
</li>
<li class="">
<a href="SubFolder3_2">
<span class="sub-item">SubFolder3_2</span>
</a>
</li>
</ul>
</div>
</li>
</ul>
any idea?