0

I want to make a menu, and change the class of parent li and child li when clicking.

When I click on the li with no class="active", I want jQuery to add a class on the empty li and its child li and remove it from the others li.

I tried following script but it didn't work for me:

$('.menu .list li > ul > li > a').click(function () {
  $('li').removeClass();
  $(this).parent().addClass('active');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
    <ul class="list">
        <li class="active">
            <a href="/Employee/Profile">
                <i class="material-icons">person</i>
                <span>Profile</span>
            </a>
        </li>
        <li>
            <a href="javascript:void(0);" class="menu-toggle">
                <i class="material-icons">subject</i>
                <span>Leaves</span>
            </a>
            <ul class="ml-menu">
                <li>
                    <a href="/Admin/AllEmployees">Show My Leaves</a>
                </li>
                <li>
                    <a href="/Leaves/RequestForLeave">Request for Leave</a>
                </li>
                
            </ul>
        </li>
    </ul>
</div>

Please help me to write the script.

Coli
  • 927
  • 8
  • 28
Tejas
  • 381
  • 1
  • 7
  • 25

1 Answers1

0

You might try this code.

<script>
    $('.menu .list li > ul > li > a').click(function () {
       $('.menu .list li').each(function(){ $(this).removeClass() });
       $(this).parent().addClass('active');
    });
</script>
MTCoster
  • 5,868
  • 3
  • 28
  • 49
Mr Cho
  • 1
  • $('.menu .list li > ul > li > a').click(function () { $('.menu .list li').each(function(){ $(this).removeClass() }); $(this).parents().addClass('active'); }); – Mr Cho Nov 17 '18 at 11:10
  • try this. not parent. parents – Mr Cho Nov 17 '18 at 11:11
  • I tried this one. and i hope this is that you want https://jsfiddle.net/#&togetherjs=ARG9TCib0p – Mr Cho Nov 17 '18 at 11:12
  • As you are clicking an anchor link , which on click redirect page to another location so this case if you want to add active link on current menu item you will need to check the current url with the menu item and then add active class Please check this thread : https://stackoverflow.com/questions/20060467/add-active-navigation-class-based-on-url https://medium.com/jquery-code-snippets/add-active-navigation-class-to-menu-item-based-on-url-using-jquery-cc88cea618e9 – Balwant Nov 17 '18 at 12:58