Nate
Nate

Reputation: 101

Find elements where class = a certain class and delete class

I have a list of divs with no class when they are clicked they get the class of 'active' however when i click the second div in the list i want any other div that is using the class of active to drop the class of active.

The HTML:-

    <div id="div1" onclick="classchanger(this); return false;"><p>first item</p></div>

    <div id="div2" onclick="classchanger(this); return false;"><p>second item</p></div>

    <div id="div3" onclick="classchanger(this); return false;"><p>third item</p></div>

The Jquery to add the class when a div is clicked:-

    function classchanger(e) {
    $(e).addClass( "active" );  

    };

However i need to remove this class should a different div be clicked on such as:- (An example of the code i'm trying to achieve.)

    function classchanger(e) {
    if(any div == class of active){ 
    the divs with a class of active .removeClass( "active" )
    }
    $(e).addClass( "active" );  
    };

Any idea on this or alternative methods i would be very thankful.

Upvotes: 1

Views: 120

Answers (2)

Loyalar
Loyalar

Reputation: 2163

You should just change your classchanger function to

function classchanger(e) {
    $("#container").find(".active").removeClass("active"); 
    $(e).addClass( "active" );  
};

The selector selects all the elements with the class "active", and removes the class from them. Then you just add the class to the element you were clicking on.

Upvotes: 3

Rob Sedgwick
Rob Sedgwick

Reputation: 5226

HTML

   <div id="div1" class="item"><p>first item</p></div>
    <div id="div2" class="item"><p>second item</p></div>
    <div id="div3" class="item"><p>third item</p></div>

JS (jquery )

$(".item").on("click",function() {
  $(".item").each(function() { $(this).removeClass("active"); });
  $(this).addClass("active");
});

Upvotes: -2

Related Questions