Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have:
<ul id="FirstLevel">
<li><a href="#">FirstLevel</a></li>
<li><a href="#">FirstLevel</a>
<ul class="secondLevel">
<li><a href="#">SecondLevel</a></li>
<ul class="LastLevel">
<li><a href="#">LastLevel</a></li>
<li><a href="#">LastLevel</a></li>
</ul>
<li><a href="#">SecondLevel</a></li>
<li><a href="#">SecondLevel</a></li>
</ul>
</li>
<li><a href="#">FirstLevel</a></li>
<li><a href="#">FirstLevel</a></li>
<li><a href="#">FirstLevel</a></li>
</ul
I am looking for a solution where, on clicking a child element with the class LastLevel
or SecondLevel
, a class should be added to the parent li
element with the class FirstLevel
. The previously selected menu state should also be removed in this process.
I attempted to achieve this functionality using jQuery, but it doesn't seem to work as expected. Here's what I tried:
$('#firstUl').find('li').click(function(){ //removing the previous selected menu state $('#firstUl').find('li').removeClass('active'); //is this element from the second level menu? if($(this).closest('ul').hasClass('lastLevel')){ $(this).parents('li').parents('li').addClass('menuActive'); //this is a parent element }else{ $(this).addClass('menuActive'); } });
Your insights and suggestions would be greatly appreciated. Thank you.