Easiest way to toggle 2 classes in jQuery

Stewie Griffin picture Stewie Griffin · Aug 9, 2011 · Viewed 197k times · Source

If I have class .A and class .B and want to switch in between on button click, what's a nice solution for that in jQuery? I still don't understand how toggleClass() works.

Is there an inline solution to put it in onclick="" event?

Answer

Frédéric Hamidi picture Frédéric Hamidi · Aug 9, 2011

If your element exposes class A from the start, you can write:

$(element).toggleClass("A B");

This will remove class A and add class B. If you do that again, it will remove class B and reinstate class A.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".A, .B").toggleClass("A B");