skip to Main Content

I have some same elements with the following HTML code:

<ul class="nav-list">
    <li>
        <a href="#">
            <i class="fa-solid fa-layer-group"></i>
            <span class="links_name">My First Item</span>
        </a>
    </li>
</ul>

I want to add selected class to the clicked item and remove that class from all other same classes.
I use the following JQuery code to add a class to only selected ul:

$('.nav-list').click(function(){
    $('.nav-list li a').removeClass('selected');
    $('.sidebar ul li a').addClass('selected');
});

But all the same elements get that specific class.
What is the solution?

2

Answers


  1. Try adding the event listener directly to the child elements themselves:

    $('.nav-list').children().click(function(){
        $(this).addClass('selected');
    });
    

    So you directly can select the element clicked.

    Login or Signup to reply.
  2. Set the listener to the anchor elements, then use the "this" keyword to access the clicked element and give it the class

     $('.nav-list li a').click(function () {
      $(this).addClass('selected');
     });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search