jQuery toggleClass() Method — Toggle CSS Classes

Beginner
5 min read
Updated: Oct 2026
4 examples
Live preview

What Is toggleClass()?

.toggleClass(className) adds a CSS class when it is missing and removes it when it is present (since jQuery 1.0). Optional state forces add/remove (1.3+); arrays work since 3.3.

Remember
$("div").toggleClass("highlight")           // flip
$("div").toggleClass("highlight", true)     // force on
$("div").toggleClass("a b")                 // each name flips
$("div").toggleClass(["a", "b"])            // array (3.3+)

// true  → like .addClass()
// false → like .removeClass()
NeedUse
Flip a class$el.toggleClass("active")
Force on$el.addClass("active")
Force off$el.removeClass("active")
Test presence$el.hasClass("active")

How to Use toggleClass()

Select elements, pass class names, optionally force a boolean state.

  1. Select the element(s) with a jQuery selector.
  2. Call .toggleClass("name") — or a space-separated list / array.
  3. Optional: pass true/false as the second argument to force on/off.
  4. Chain freely — .toggleClass() returns the same jQuery object.
PieceRequired?Role
className / array / functionYes*Class(es) to flip (*required in modern jQuery)
stateNotrue add, false remove (strict boolean)
Return—Same jQuery collection (chainable)

Pseudocode

Pseudocode
function toggleClass(selection, names, state):
    for each el in selection:
        classes = resolve names (string | array | function)
        for each class in classes:
            if state is true:
                add class
            else if state is false:
                remove class
            else if el has class:
                remove class
            else:
                add class
    return selection

Cheat Sheet

Keep these facts handy when flipping classes.

TopicDetail
Syntax.toggleClass(className[, state])
Since1.0 (state: 1.3; array: 3.3)
MultipleSpace string or array of names
Force on/offSecond arg must be a real boolean
CallbackSince 1.4 — return class name(s)
Native cousinelement.classList.toggle()

Live Preview

Flip classes on a sample element and watch the class attribute update.

Sample box (class shown below)

Browser demo of .toggleClass() — same idea as the examples below.

Result
class="tumble"

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Toggle a Class on Click

Official style: flip highlight each time a paragraph is clicked.

jQuery
$("p").on("click", function () {
  $(this).toggleClass("highlight");
  console.log(this.className);
});
// first click  → "… highlight"
// second click → highlight removed
Try It Yourself

How It Works

  1. Click handler. Each paragraph toggles itself with $(this).
  2. Missing class. First click adds highlight.
  3. Present class. Next click removes it.
  4. No state tracking. jQuery checks the current class list for you.

Example 2 — Force With a Boolean State

Official pattern: add highlight only every third click.

jQuery
var count = 0;
$("p").on("click", function () {
  count++;
  $(this).toggleClass("highlight", count % 3 === 0);
  console.log(count, this.className);
});
// clicks 1–2 → highlight off
// click 3    → highlight on
Try It Yourself

How It Works

  1. Count clicks in a variable outside the handler.
  2. Boolean. count % 3 === 0 is a real true/false.
  3. Force. true adds; false removes — no flip surprise.
  4. Same as branching to .addClass() / .removeClass().

Example 3 — Toggle Several Classes

Each listed class flips independently.

jQuery
var $box = $("<div class='a'></div>");
$box.toggleClass("a b");
console.log($box.attr("class"));  // "b"

$box.toggleClass(["a", "b"]);
console.log($box.attr("class"));  // "a"
Try It Yourself

How It Works

  1. Start. Element has class a only.
  2. String. "a b" removes a and adds b.
  3. Array. ["a", "b"] flips both again → back to a.
  4. Independent. Each name is decided on its own presence.

Example 4 — Choose the Class With a Function

Return different class names based on context (since 1.4).

jQuery
$("div.foo").toggleClass(function () {
  if ($(this).parent().is(".bar")) {
    return "happy";
  }
  return "sad";
});
console.log($("div.foo").attr("class"));
Try It Yourself

How It Works

  1. Per element. jQuery calls your function once for each match.
  2. Decide. Return the class name(s) to toggle for that element.
  3. Parent check. Official demo uses .parent().is(".bar").
  4. Result. Only those returned names are flipped.

Edge Cases & Pitfalls

Watch these before relying on toggles in UI code.

boolean

State must be a real boolean

Use true/false, not truthy numbers or strings. Official docs warn that only a boolean forces add/remove.

exclusive

Not for exclusive tabs

When only one item should be active, clear others with .removeClass() then .addClass().

deprecated

Do not omit class names

No-arg “toggle everything” is gone in jQuery 4. Always name the classes you flip.

check

Need to test first?

Use .hasClass() when you only want to know presence without changing anything.

Browser Support

.toggleClass() has shipped since jQuery 1.0 (boolean state since 1.3; arrays since 3.3). It works in all modern browsers with jQuery loaded.

✓ jQuery 1.0+

.toggleClass()

Supported everywhere jQuery runs in the browser. Prefer named classes; avoid the removed no-arg form.

100% Browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.toggleClass() Excellent

Bottom line: Call .toggleClass("name") to flip, or pass a boolean state to force add/remove.

Performance Notes

ApproachCostBest for
.toggleClass(name)CheapUI toggles / click handlers
.toggleClass(name, state)CheapKnown desired state
classList.toggleCheapNative one-element flips

Class toggles are inexpensive. Prefer classes over frequent .css() writes when styles live in a stylesheet.

Key Takeaways

  • Role: flip a class on or off in one call.
  • State: pass true/false to force add or remove.
  • Multiple: space string or array — each name flips alone.
  • Modern: always pass class names — no-arg form is removed.

One line: .toggleClass("name") flips; .toggleClass("name", state) forces on or off.

Frequently Asked Questions

.toggleClass(className) adds a class when it is missing and removes it when it is present — flipping the class on or off in one call. It updates the class attribute so stylesheet rules apply or stop applying.
.addClass() always adds; .removeClass() always removes. .toggleClass() inspects each element and flips the class. Use it for click-to-highlight, open/close UI, and theme switches without tracking state yourself.
Since jQuery 1.3, .toggleClass(className, state) forces the result: true adds (like .addClass()), false removes (like .removeClass()). Handy when you already know the desired state, e.g. count % 3 === 0.
Yes. Pass a space-separated string or, since jQuery 3.3, an array. Each listed class is toggled independently on every matched element.
Since jQuery 1.4, pass a function that returns the class name(s) to toggle. jQuery calls it once per element with index, current className, and state. Since 3.3 it may return an array.
No. Calling .toggleClass() with only an optional boolean (toggling all classes) was deprecated in jQuery 3.0 and removed in 4.0. Always pass the class name(s) you mean to flip.

Next: css()

Learn how to get and set inline CSS properties with jQuery.

css() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful