Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Assign class on clicked element of multiple count

Tags:

jquery

class

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>
like image 441
CobaltBabyBear Avatar asked Jan 13 '23 20:01

CobaltBabyBear


2 Answers

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

like image 72
T.J. Crowder Avatar answered Jan 19 '23 10:01

T.J. Crowder


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.

CHECKOUT THE DEMO

like image 27
Jai Avatar answered Jan 19 '23 12:01

Jai