add/remove active class for ul list with jquery?
you can use siblings and removeClass method
$('.nav-link li').click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
this
will point to the <ul>
selected by .nav-list
. You can use delegation instead!
$('.nav-list').on('click', 'li', function() {
$('.nav-list li.active').removeClass('active');
$(this).addClass('active');
});
Try this,
$('.nav-list li').click(function() {
$('.nav-list li.active').removeClass('active');
$(this).addClass('active');
});
In your context $(this)
will points to the UL
element not the Li
. Hence you are not getting the expected results.
I used this:
$('.nav-list li.active').removeClass('active');
$(this).parent().addClass('active');
Since the active class is in the <li>
element and what is clicked is the <a>
element, the first line removes .active
from all <li>
and the second one (again, $(this)
represents <a>
which is the clicked element) adds .active
to the direct parent, which is <li>
.