jQuery .toggleClass(): Toggle a Class or Set Its State
.toggleClass("name") removes the class if it is present and adds it if absent. A second argument of true or false explicitly determines whether the class should be present.
Syntax and behavior
$("#item").toggleClass("active");
$("#item").toggleClass("active", true);
$("#item").toggleClass("active", false);
Toggling a state differs from setting a state. Use the one-argument form for a click that reverses a highlight. Use the state argument when reflecting an existing checkbox or server value. The state must be a Boolean value, not the string "false" or the number 0. Multiple class names are handled individually. This method returns the original jQuery object.
The official jQuery .toggleClass() documentation describes additional call signatures and argument types.
Complete runnable example
Save the following code as a UTF-8 example.html file and open it in a browser. It loads the full jQuery 4.0.0 build from an external URL, so an internet connection is required. The $(function () { ... }) callback waits for the document to be ready before running the example.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery toggleClass example</title>
<style>
body { margin: 24px; font-family: sans-serif; line-height: 1.6; }
.marked { background: #fff0b3; border: 2px solid #835b00; }
.active { color: #a00000; font-weight: bold; }
button, input, select { font: inherit; }
#output { white-space: pre-wrap; overflow-wrap: anywhere; }
</style>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
<button id="toggle" type="button" aria-pressed="false">Toggle highlight</button>
<p id="item" class="base">Paragraph to toggle</p>
<p id="output" aria-live="polite"></p>
<script>
$(function () {
$("#toggle").on("click", function () {
$("#item").toggleClass("active");
const enabled = $("#item").hasClass("active");
$(this).attr("aria-pressed", String(enabled));
$("#output").text("Highlighted: " + enabled);
});
});
</script>
</body>
</html>
Expected result
The first click highlights the paragraph and displays Highlighted: true. A second click removes the class and displays Highlighted: false. The button’s aria-pressed attribute is updated to match its pressed state.
Important details and troubleshooting
- Repeatedly toggling a class can get out of sync with the underlying condition. Use .toggleClass("active", enabled) when matching a known state.
- jQuery 4.0 removed the no-class-name forms .toggleClass() and .toggleClass(state), which previously toggled the entire class attribute. Name the class to change.
- Changing a class does not automatically update visibility or accessibility state. Maintain the appropriate CSS and ARIA attributes for the control’s purpose.
Compare the behavior with .addClass() and CSS classes, .removeClass() and class removal.










