jQuery switchClass example

« Back to main page

This plugin provides functionality similar to toggleClass, but instead of adding/removing a single class from an element, switchClass toggles between TWO classes ensuring that one and only one of the two classes is assigned to an element (or elements) at one time. It leaves all other element classes untouched and only affects the two classes specified.

In practical terms, one example usage would be for toggling a table row's class from "odd" to "even" classes after a row has been deleted.


Code usage

// toggles the element(s) between class1 and class2
$(...).switchClass("class1", "class2");

// ensures that ONLY class1 is assigned to the element(s) out of the two classes (leaves other classes untouched)
$(...).switchClass("class1", "class2", "class1");
			

Example

The following example has two classes defined: .blue and .green. Click the various buttons to see the result of each.

The first row
The second row
The third row
The fourth row