I need to be able to toggle class when I click an element. It works fine for that element:
$(".main").click(function() { $(this).toggleClass("classA").toggleClass("classB"); });
But I would like to add to it to toggle classes for all elements on the page that have a particular class, say "togToo". For those elements I need to toggle between "classC" and "classD".
I'm almost certain there's a way to combine that into one click...
^^^ UPDATED ABOVE ^^^
Answer. Yes, you can toggle multiple classes using a single . toggleClass() call. To do so, you can separate the class names with spaces.
JavaScript Toggle Class Multiple ElementsYou can also toggle class on multiple element at once. For this target multiple elements and use the toggle() method. To toggle a class on multiple elements select those elements and apply the toggle method on each element to handle their corresponding class.
The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.
To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.
If the elements to be toggled start off with one of the two classes, you can then toggle back and forth like this:
$('#element_to_click').click( function(){ $('.togToo').toggleClass('classC classD'); });
Answer Updated
$(".main").click(function() { $(this).toggleClass("classA").toggleClass("classB"); $('.togToo').toggleClass("classC").toggleClass("classD"); })
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