I’m building a multi level menu and would like to add an active class to the element through a function (which is working) but would also want to add this class to it parents elements.
<ul class="main-menu">
<li><a href="#" class="nav-link">Maine Level 1</a>
<ul>
<li><a class="nav-link" scene="scene_1">Scene 1</a></li>
<li><a class="nav-link" scene="scene_2">Scene 2</a></li>
</ul>
</li>
<li><a href="#" class="nav-link">Maine Level 2</a>
<ul>
<li><a class="nav-link" scene="scene_3">Scene 3</a></li>
<ul>
<li><a class="nav-link" scene="scene_3.1">Scene 3.1</a></li>
<li><a class="nav-link" scene="scene_3.2">Scene 3.2</a></li>
</ul>
<li><a class="nav-link" scene="scene_4">Scene 4</a></li>
</ul>
</li>
</ul>
the function :
function set_active_scene(name){
$("ul.main-menu ul li a").each(function() {
$(this.closest('li')).removeClass("active");
if ($(this).attr("scene") == name)
$(this.closest('li')).addClass("active");
});
}
I tried with $(this.parents('li')).addClass("active");
but it’s not working.
Any idea ?
2
Answers
If you only want to add the "active" class to the immediate parent li element of the active anchor element, you can simply use parent(). Here’s the modified function:
With this modification, only the immediate parent of li element of the active a element will receive the "active" class, not all parent li elements up the DOM tree.
this and $(this) are not same. Here
this
refers to the actual DOM i.e.<a class="nav-link" scene="scene_1">Scene 1</a>
.parents()
andclosest()
are jQuery function so,this
needs to be$(this)
.See the following example.