I have a list of clickable elements, all with same class names. I want to assign the clicked element a class active
and remove active
from all other elements simultaneously. How do I do it through jQuery?
<div class="container">
<div class="element"></div>
<div class="element active"></div>
<div class="element"></div>
</div>
Just hook click
on .element
elements, remove active
from any .element
elements that have it, and add it to the clicked one:
$(".element").click(function() {
$(".element.active").removeClass("active");
$(this).addClass("active");
});
More: jQuery/$
, click
, removeClass
, addClass
use addClass()
and .siblings()
this way:
$('.element').click(function(){
$(this).addClass('active').siblings().removeClass('active');
});
Here $(this)
is the current element which is been clicked so this element gets the class .active
and .siblings().removeClass()
is removing other .active
class applied on other element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With