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
Try adding the event listener directly to the child elements themselves:
So you directly can select the element clicked.
Set the listener to the anchor elements, then use the "this" keyword to access the clicked element and give it the class