Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle multiple element classes with jQuery

Tags:

jquery

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 ^^^

like image 779
santa Avatar asked Mar 31 '11 19:03

santa


People also ask

How do you toggle with multiple classes?

Answer. Yes, you can toggle multiple classes using a single . toggleClass() call. To do so, you can separate the class names with spaces.

Can I toggle multiple classes JavaScript?

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.

What is toggleClass in jQuery?

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.

How can I replace one class with another in jQuery?

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.


2 Answers

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'); }); 
like image 118
Ken Redler Avatar answered Sep 19 '22 07:09

Ken Redler


Answer Updated

$(".main").click(function() {     $(this).toggleClass("classA").toggleClass("classB");     $('.togToo').toggleClass("classC").toggleClass("classD"); }) 
like image 40
Naftali Avatar answered Sep 18 '22 07:09

Naftali