The .toggleClass() method adds a CSS class when it is missing and removes it when present — one call flips stylesheet-driven styling on or off. This tutorial covers all API overloads (string, boolean state, array, callback, no-args), comparisons with .addClass(), .removeClass(), and .css(), and the official click-to-highlight pattern.
01
String
Flip on/off
02
Boolean
Force state
03
Array
Since 3.3
04
Callback
Per element
05
vs add/remove
When to use
06
Since 1.0
Core API
Fundamentals
Introduction
Styling in modern web pages usually lives in CSS files — reusable class names like .active, .highlight, or .dark-theme that you flip on elements at runtime. When JavaScript needs to switch a style on or off without tracking whether the class is already there, jQuery provides .toggleClass().
Available since jQuery 1.0, .toggleClass() updates the class attribute on each matched element. It adds the specified class when missing and removes it when present — a single method for binary on/off states. For always-on or always-off changes, use .addClass() or .removeClass(). For inline property values, use .css() instead.
Concept
Understanding the .toggleClass() Method
Given a jQuery object representing one or more DOM elements, .toggleClass() flips the specified class name(s) on each element. If the class is absent, jQuery adds it and stylesheet rules apply. If the class is already there, jQuery removes it and those rules stop applying — no need to check .hasClass() first.
Think of classes as labels you stick onto elements. .addClass() always adds more labels; .removeClass() always peels them off; .toggleClass() checks each label and flips it. For exclusive state switches across a group — only one tab active — chain .removeClass() then .addClass() instead.
💡
Beginner Tip
$("p").on("click", function() { $(this).toggleClass("highlight"); }) adds highlight on first click and removes it on the next — perfect for click-to-select rows or paragraphs.
Foundation
📝 Syntax
jQuery .toggleClass() accepts several argument forms:
1. String — toggle one or more class names (since 1.0)
jQuery
.toggleClass( className )
className — a string of one or more space-separated CSS class names. Each listed class is added if missing or removed if present.
2. String with boolean state (since 1.3)
jQuery
.toggleClass( className, state )
className — the CSS class name(s) to add or remove.
state — a boolean: true adds the class (like .addClass()); false removes it (like .removeClass()).
3. Array — list of class names (since 3.3)
jQuery
.toggleClass( [ classNames ] )
classNames — an array of strings; jQuery toggles every entry on each element.
4. Array with boolean state (since 3.3)
jQuery
.toggleClass( [ classNames ], state )
state — when true, all listed classes are added; when false, all are removed.
5. Function — per-element class name(s) (since 1.4)
jQuery
.toggleClass( function( index, className, state ) {
// return className string
} [, state ] )
index — zero-based index of the element within the matched set.
className — the element’s current class attribute value (or empty string).
state — whether the class is currently present (true) or absent (false).
Return a string of class name(s) to toggle for that element. Optional outer state boolean forces add (true) or remove (false).
6. Function returning array (since 3.3)
The callback may return an array of class names instead of a space-separated string:
jQuery
$( "li" ).toggleClass( function( index ) {
return [ "item-" + index, "row-" + index ];
} );
7. No arguments — toggle all classes (since 1.4)
jQuery
.toggleClass()
With no arguments, jQuery toggles every class on each matched element on the first call — use carefully; prefer naming specific classes instead.
Return value
The original jQuery object (for chaining) — not a new collection.
Official jQuery API click pattern
jQuery
$( "p" ).on( "click", function() {
$( this ).toggleClass( "highlight" );
} );
// Each click flips highlight on or off — no hasClass check needed
📋 .toggleClass() vs .addClass() vs .removeClass() vs .css()
Four styling approaches — flip classes, append classes, strip classes, or set inline properties.
.toggleClass()
on/off
Add if missing, remove if present
.addClass()
+ class
Append class names — keeps existing classes
.removeClass()
- class
Strip one, some, or all classes
.css()
inline
Set style properties directly on the element
Hands-On
Examples Gallery
Examples 1–4 follow the official jQuery API documentation. Example 5 shows a practical dark-theme switch on body. Use DevTools or the Try-it links to run each snippet in the browser.
📚 Getting Started
Official jQuery demos for toggling CSS classes.
Example 1 — Official Demo: Click to Toggle highlight
Flip the highlight class each time a paragraph is clicked.
First click on a paragraph → class "highlight" added (yellow background)
Second click → class "highlight" removed
Other classes (e.g. "blue") → unchanged throughout
How It Works
Each click inspects whether highlight is present. jQuery adds it when missing and removes it when present — no separate .hasClass() branch needed.
Example 2 — Official Demo: Boolean State With count % 3 === 0
Force highlight on only when the click count is divisible by three.
Clicks 1, 2 → highlight removed (state false)
Click 3 → highlight added (state true)
Clicks 4, 5 → highlight removed again
Pattern repeats every third click
How It Works
The second argument overrides flip behavior: true acts like .addClass(), false like .removeClass(). Use this when your logic already computes the desired state.
Example 3 — Official Demo: Buttons Toggle Classes on Divs
Each button’s own class list is toggled on every box in the wrapper.
Button "toggle a" → class "a" flipped on all divs
Button "toggle a b" → classes "a" and "b" flipped together
Each class toggled independently — present removed, absent added
Reset button clears all classes via .attr("class", "")
How It Works
jQuery reads the button’s space-separated className string and toggles every listed class on each matched div. Multiple classes in one string are handled in a single call.
Example 4 — Array Syntax: Toggle bold and italic (jQuery 3.3+)
Pass an array when class names already live in a JavaScript array.
First click → bold and italic added to #box
Second click → both classes removed
Same flip behavior as a space-separated string
Useful when class names come from a variable or API response
How It Works
The array form (added in jQuery 3.3) avoids building a space-separated string manually — each entry is toggled independently on the element.
📈 Practical Patterns
Use .toggleClass() for theme switches and other global on/off states on a single element.
Example 5 — Dark Theme Toggle on body
Flip a dark-theme class on body to switch the entire page appearance.
First click → body gains class "dark-theme" (dark background, light text)
Second click → "dark-theme" removed — page returns to light mode
CSS handles all visual changes — JavaScript only flips one class
How It Works
Styles for light and dark modes live in CSS (body.dark-theme { … }). One class toggle on body cascades to child elements — a common pattern for theme switches without inline styles.
Applications
🚀 Common Use Cases
Click-to-highlight — $(this).toggleClass("selected") on table rows or list items.
Panel open/close — $(".panel").toggleClass("open") to show or hide with CSS transitions.
Dark mode switch — $("body").toggleClass("dark-theme") on a button click.
Conditional highlight — $(el).toggleClass("error", !isValid) with boolean state.
Multi-class styling — $(box).toggleClass("bold italic") or array form for computed names.
Exclusive tab state — prefer .removeClass("active").addClass("active") across siblings, not .toggleClass().
🧠 How .toggleClass() Updates Elements
1
Match elements
jQuery object holds one or more DOM nodes to update.
Input
2
Resolve class names
String, array, callback, or no-args — optional boolean forces add/remove.
Parse
3
Flip class attribute
Each listed class added if missing, removed if present — or forced by state.
DOM
4
🎨
Styles update
CSS rules for toggled classes apply or stop — return same jQuery object for chaining.
Important
📝 Notes
Available since jQuery 1.0 — boolean state argument since 1.3; callback since 1.4; no-args form since 1.4.
Array argument supported since jQuery 3.3; callback may return array since 3.3.
Calling .toggleClass() with no arguments toggles all classes on each element — use sparingly.
.toggleClass(state) with only a boolean (no class name) was deprecated in jQuery 3.0 and removed in 4.0 — always pass a class name or callback.
Before jQuery 1.12/2.2 used the className property; since 1.12/2.2 uses the class attribute — works on SVG and XML elements.
For exclusive state across siblings (one active tab), use .removeClass() + .addClass() instead of .toggleClass().
Returns the original jQuery object for chaining — e.g. .toggleClass("open").slideDown().
Compatibility
Browser Support
.toggleClass() has been part of jQuery since 1.0+. Boolean state arrived in 1.3+; callback in 1.4+; array arguments in 3.3+; SVG/XML support via the class attribute in 1.12+/2.2+. It relies on standard class attribute manipulation with no browser-specific quirks beyond jQuery itself.
✓ jQuery 1.0+
jQuery .toggleClass()
Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. Native equivalent: element.classList.toggle() — jQuery adds collection semantics, boolean state overload, callback forms, multi-class strings, and older-browser consistency.
100%With jQuery loaded
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
.toggleClass()Universal
Bottom line: Safe in any jQuery project. Prefer .toggleClass() for binary on/off class states; use .removeClass().addClass() for exclusive switches.
Wrap Up
Conclusion
The jQuery .toggleClass() method flips CSS class names on each matched element — adding when absent and removing when present. It is the standard way to handle binary on/off styling at runtime without tracking current state in JavaScript.
Remember the official click pattern: $("p").on("click", function() { $(this).toggleClass("highlight"); }). Use the boolean state overload when you already know whether the class should be on, reach for .removeClass().addClass() for exclusive tab switches, and use .css() only when you need dynamic inline values.
Define reusable styles in CSS and flip them with .toggleClass()
Use the boolean state form when your logic already computes on/off — .toggleClass("active", isOpen)
Use the array form when class names come from a JavaScript array (3.3+)
Use .removeClass().addClass() for exclusive state across sibling elements
Keep class names semantic — .dark-theme, .selected, not .red-bg
❌ Don’t
Call .toggleClass() with no arguments unless you truly want every class flipped
Use .toggleClass() for exclusive tab groups — clear siblings with .removeClass() first
Use .toggleClass() for one-off pixel values — use .css() instead
Rely on the deprecated boolean-only form .toggleClass(state) — removed in jQuery 4.0
Forget that toggled classes can be flipped back — the method is reversible on every call
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about .toggleClass()
Flip classes — on or off in one call.
5
Core concepts
⇄01
.toggleClass()
Flip
API
T/F02
Boolean
Force state
Syntax
−+03
add/remove
Compare
Compare
[]04
Array
3.3+
Syntax
fn05
Callback
Per item
1.4+
❓ Frequently Asked Questions
.toggleClass() adds a CSS class when it is missing from an element and removes it when it is already present — flipping the class on or off in one call. It updates the element's class attribute so stylesheet rules apply or stop applying without changing HTML content or inline style properties.
.addClass() always appends class names; .removeClass() always strips them. .toggleClass() inspects each element and adds the class if absent or removes it if present — ideal for click-to-highlight, open/close panels, and theme switches without tracking current state in JavaScript.
Since jQuery 1.3, .toggleClass(className, state) accepts a second boolean: true forces the class on (same as .addClass()), false forces it off (same as .removeClass()). Use this when your logic already knows the desired state — e.g. toggleClass('highlight', count % 3 === 0).
Yes. Pass a space-separated string — toggleClass('bold italic') — or since jQuery 3.3 an array — toggleClass(['bold', 'italic']). jQuery toggles every listed class independently on each matched element: missing classes are added, present ones are removed.
Since jQuery 1.4, you can pass a function: toggleClass(function(index, className, state) { return 'item-' + index; }). jQuery calls it once per element; the return value names class(es) to toggle. Since 3.3 the callback may return an array. An optional second boolean argument forces add (true) or remove (false) for the returned classes.
Use .removeClass().addClass() for exclusive state switches — e.g. only one tab active at a time — where you must clear other elements' classes before applying a new one. Use .toggleClass() for independent on/off toggles on the same element, such as highlighting a clicked row or flipping a dark-theme class on body.
Did you know?
jQuery’s .toggleClass() has existed since version 1.0 — the go-to method for click-to-highlight patterns. The boolean state overload (since 1.3) lets you force a class on or off without checking .hasClass() first. Since jQuery 1.12/2.2 it uses the class attribute (not the legacy className property), so it works on SVG elements too — flip .highlighted on an icon path the same way you would a <div>.