The .hasClass() method tests whether matched elements have a specific CSS class name and returns a plain Boolean — not a jQuery object. This tutorial covers single-class syntax, any-vs-all set behavior, comparisons with .is(), .toggleClass(), and .addClass(), and practical filter and form-guard patterns.
01
Boolean
true or false
02
One class
Single name only
03
Any match
True if any has it
04
vs is()
Selector test
05
vs toggle
Read vs change
06
Since 1.2
Core API
Fundamentals
Introduction
After you add classes with .addClass() or toggle them with .toggleClass(), your JavaScript often needs to read that state before deciding what to do next — enable a button, show a panel, or skip an animation. jQuery provides .hasClass() for exactly that.
Available since jQuery 1.2, .hasClass() inspects the class attribute on matched elements and returns true if at least one element carries the given class name, or false otherwise. Unlike .addClass() and most other jQuery methods, it returns a plain Boolean — not a jQuery object — so you use it inside if statements, callbacks, and filters.
Concept
Understanding the .hasClass() Method
Given a jQuery object representing one or more DOM elements, .hasClass( className ) checks whether any element in that collection has the specified class. It is a read-only operation — it never modifies the DOM or the element’s classes.
Think of it as asking a yes-or-no question: “Does this element (or any element in this set) have the class selected?” Pair it with .addClass() and .removeClass() when you need conditional logic, or with .filter() when you need to narrow a collection to elements that already carry a state class.
💡
Beginner Tip
$("p").first().hasClass("selected") tests one paragraph. $("p").hasClass("selected") returns true if any paragraph has that class — a subtle but important difference.
Foundation
📝 Syntax
jQuery .hasClass() accepts one argument form:
String — single class name (since 1.2)
jQuery
.hasClass( className )
className — a single CSS class name to test (one name per call — not a space-separated list).
Return value
A plain Boolean — true if at least one matched element has the class, false otherwise.
Not chainable as a jQuery method — store the result or use it in a condition.
Important note
⚠️
One class per call
Pass only one class name: .hasClass("foo"). Do not pass "foo bar" expecting both — jQuery looks for a class literally named foo bar, which is almost never what you want. Test multiple classes with separate calls.
📋 .hasClass() vs .is() vs .toggleClass() vs .addClass()
Four related approaches — read class state, match selectors, flip classes, or append classes.
.hasClass()
? class
Test one class name — returns Boolean
.is()
? selector
Match against any selector — also Boolean
.toggleClass()
on/off
Add if missing, remove if present — changes DOM
.addClass()
+ class
Append class names — always adds, never tests
Hands-On
Examples Gallery
Examples 1–2 follow the official jQuery API documentation. Examples 3–5 show conditional toggles, filtering, and form guards. Use DevTools or the Try-it links to run each snippet in the browser.
📚 Getting Started
Official jQuery demos for testing CSS classes.
Example 1 — Official Demo: Test selected on First, Last, and Any Paragraph
Append .toString() to display the Boolean result in the page.
First paragraph has selected class: false
Second paragraph has selected class: true
At least one paragraph has selected class: true
How It Works
.first() and .last() narrow to one element before testing. Calling .hasClass() on all paragraphs returns true when any paragraph in the set has the class.
Example 2 — Official Demo: Multiple Classes on One Element
An element with class="foo bar" — test each class name separately.
Click card without highlight → .addClass("highlight") — yellow background
Click again → .removeClass("highlight") — back to default
Same effect as .toggleClass("highlight") but explicit branch logic
How It Works
.hasClass() reads current state; .addClass() and .removeClass() change it. For simple on/off you could use .toggleClass(), but explicit if/else makes the intent clear and allows different actions per branch.
Example 4 — Filter List Items With .hasClass("done")
Count and show only completed tasks using .filter() with a callback.
Completed tasks: 2
"Show completed only" → hides non-done items, shows li.done
"Show all" → restores full list
How It Works
Inside .filter(), return true to keep an element. $(this).hasClass("done") tests each <li> individually — unlike calling .hasClass() on the whole list, which would only tell you if any item is done.
Example 5 — Form Guard: Enable Submit When #terms Has Class checked
Keep the submit button disabled until the user accepts terms.
jQuery
function syncSubmit() {
var ok = $( "#terms" ).hasClass( "checked" );
$( "#submit" ).prop( "disabled", !ok );
}
$( "#terms" ).on( "click", function() {
$( this ).toggleClass( "checked" );
syncSubmit();
} );
Initial state → Submit disabled (no .checked class)
Click terms → .toggleClass("checked") → hasClass("checked") is true → Submit enabled
Click again → class removed → Submit disabled again
How It Works
.toggleClass() updates the visual state on click; .hasClass("checked") reads that state to drive the button’s disabled property. Classes act as a simple state flag without extra variables.
Applications
🚀 Common Use Cases
Conditional styling — if (!$el.hasClass("active")) { $el.addClass("active"); } before running an animation.
Filter collections — $("li").filter(function(){ return $(this).hasClass("done"); }) to count or show completed items.
Form validation gates — $("#terms").hasClass("checked") before enabling submit or proceeding to the next step.
Skip redundant updates — if (!$panel.hasClass("open")) { $panel.addClass("open"); } to avoid re-triggering transitions.
Menu state checks — if ($("nav").hasClass("mobile-open")) { ... } before closing or measuring layout.
Plugin initialization guard — if (!$el.hasClass("plugin-initialized")) { initPlugin($el); $el.addClass("plugin-initialized"); }.
🧠 How .hasClass() Inspects Elements
1
Match elements
jQuery object holds one or more DOM nodes to inspect.
Input
2
Read class attribute
jQuery reads each element’s class attribute value.
Parse
3
Token match
Compares the requested class name against space-separated tokens.
Check
4
✅
Return Boolean
true if any matched element has the class; false otherwise — no DOM changes.
Important
📝 Notes
Available since jQuery 1.2 — core class inspection API.
Returns a plain Boolean — not a jQuery object; cannot chain further jQuery methods.
Accepts only one class name per call — not a space-separated list.
On a multi-element set, returns true if any element has the class.
Read-only — does not add, remove, or toggle classes.
SVG and XML elements supported since jQuery 1.12.
Compatibility
Browser Support
.hasClass() has been part of jQuery since 1.2+. SVG/XML support arrived in 1.12+. It relies on standard class attribute inspection with no browser-specific quirks beyond jQuery itself.
✓ jQuery 1.2+
jQuery .hasClass()
Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. Native equivalent: element.classList.contains() — jQuery adds collection semantics and any-match behavior across sets.
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
.hasClass()Universal
Bottom line: Safe in any jQuery project. Use .hasClass() to read class state; use .addClass(), .removeClass(), or .toggleClass() to change it.
Wrap Up
Conclusion
The jQuery .hasClass() method tests whether matched elements carry a specific CSS class name and returns a plain Boolean. It is the standard read-only check before conditional styling, filtering, or form validation — without modifying the DOM.
Remember the official demo: $("p").first().hasClass("selected") tests one element, while $("p").hasClass("selected") returns true if any paragraph matches. Pair it with .addClass() and .removeClass() for branches, .filter() for per-element tests, and reach for .is() when you need full selector matching.
Narrow to one element with .first(), .eq(), or a specific selector before testing
Use .hasClass() inside .filter() callbacks for per-element checks
Test multiple required classes with separate calls combined by &&
Store the Boolean in a variable when you need it more than once
Use classes as state flags (e.g. .checked, .open) and read them with .hasClass()
❌ Don’t
Expect .hasClass() to return a jQuery object for chaining
Pass space-separated class names — test one class per call
Assume .hasClass() on a set means all elements have the class — it means any
Use .hasClass() to add or remove classes — use the appropriate mutation method
Forget that .toggleClass() may be simpler when you only need on/off without branching
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about .hasClass()
Read class state — returns Boolean.
5
Core concepts
?01
.hasClass()
Boolean
API
102
One name
Per call
Syntax
any03
Any match
In set
Behavior
.is()04
Selector
Compare
Compare
1.205
Since 1.2
SVG 1.12
Version
❓ Frequently Asked Questions
.hasClass() checks whether at least one element in the current jQuery collection has the specified CSS class name. It reads the element's class attribute and returns true or false — it does not add, remove, or toggle classes.
No. Unlike most jQuery methods, .hasClass() returns a plain Boolean — true or false — not a jQuery object. You cannot chain further jQuery methods after .hasClass(); store the result in a variable or use it inside an if statement.
It checks whether any matched element has the class. If even one element in the set has the class, .hasClass() returns true. To test a single element, narrow the set first with .first(), .last(), .eq(), or a more specific selector.
No. .hasClass() accepts only one class name per call — not a space-separated list. An element may carry many classes (e.g. class="foo bar"), but you must call .hasClass("foo") and .hasClass("bar") separately. To require both classes, combine two checks with &&.
.hasClass() tests a single class name and returns a Boolean. .is() matches elements against a full selector string (e.g. ":visible", ".active") and also returns Boolean. .toggleClass() adds or removes a class — it changes the DOM; .hasClass() only reads state.
Yes, since jQuery 1.12 .hasClass() supports SVG and XML elements in addition to HTML. Class detection on SVG follows the same API — useful for checking states on icons and vector graphics before updating them.
Did you know?
jQuery’s .hasClass() has existed since version 1.2 — one of the earliest read-only class methods. Unlike .addClass(), it returns a plain JavaScript Boolean, so you can write if ($("#menu").hasClass("open")) { ... } directly. Since 1.12 it works on SVG elements too — so you can test whether an icon path has .active the same way you would a <div>.