user2250471
user2250471

Reputation: 1112

remove class from multiple elements

I have a long list of elements all with unique IDs, and I want to be able to switch between them by clicking on them. So, if the element is on, the class is "plus on", and every other element will be simply "plus". I'm having trouble reverting previously clicked elements back to just "plus", though. This is the code I have that's not working:

$(".plus").on("click", function () {
    $(".plus").removeClass("on");
});

This part does work, for turning the element on:

        function switch(elem) {
        var elem = document.getElementById(elem);
        elem.className = 'plus on';
        }

I tried putting the click function inside and then before the switch function, but i can't get anything to work.

Upvotes: 0

Views: 156

Answers (3)

Naveen Chandra Tiwari
Naveen Chandra Tiwari

Reputation: 5123

Try this :-

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

Upvotes: 0

Rob Sedgwick
Rob Sedgwick

Reputation: 5226

$(".plus").on("click", function () {
    $(this).toggleClass("on");
});

Might be what you mean, works for the current clicked element by toggling the class

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173542

For a simple toggle between elements of the same class, you can use a more efficient method by keeping the currently selected element:

var $current = null;

$('.plus').on('click', function() {
    if ($current) {
        $current.removeClass('on');
    }
    $current = $(this).addClass('on');
}

As mentioned in the comments, if elements are added dynamically, it would be better to use event delegation; for example:

$(document).on('click', '.plus', function() {

Important: Instead of document you should choose an element that's an ancestor of your nodes that will not be removed from the document.

Upvotes: 1

Related Questions