jQuery .hasClass() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Class check

What You’ll Learn

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

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.

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.

📝 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 Booleantrue 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.

Official jQuery API example

jQuery
$( "p" ).first().hasClass( "selected" );   // false
$( "p" ).last().hasClass( "selected" );    // true
$( "p" ).hasClass( "selected" );           // true — any match

⚡ Quick Reference

GoalCode
Test one element$("p").first().hasClass("selected")
Test if any in set$("p").hasClass("selected")
Conditional add/removeif ($el.hasClass("on")) { $el.removeClass("on"); }
Filter by class$("li").filter(function(){ return $(this).hasClass("done"); })
Test two classes (both required)$el.hasClass("foo") && $el.hasClass("bar")
Full selector test instead$("div").is(":visible")

📋 .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

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.

jQuery
$( "#result1" ).append( $( "p" ).first().hasClass( "selected" ).toString() );
$( "#result2" ).append( $( "p" ).last().hasClass( "selected" ).toString() );
$( "#result3" ).append( $( "p" ).hasClass( "selected" ).toString() );
Try It Yourself

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.

jQuery
var $div = $( "#mydiv" );

$div.hasClass( "foo" );   // true
$div.hasClass( "bar" );   // true
$div.hasClass( "quux" );  // false
Try It Yourself

How It Works

Elements can carry many classes, but .hasClass() checks one name at a time. #mydiv has both foo and bar, but not quux.

📈 Practical Patterns

Use .hasClass() for conditional logic, filtering, and form validation.

Example 3 — Conditional Toggle With .hasClass()

If the element already has highlight, remove it; otherwise add it.

jQuery
$( ".card" ).on( "click", function() {
  var $el = $( this );
  if ( $el.hasClass( "highlight" ) ) {
    $el.removeClass( "highlight" );
  } else {
    $el.addClass( "highlight" );
  }
} );
Try It Yourself

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.

jQuery
var done = $( "#tasks li" ).filter( function() {
  return $( this ).hasClass( "done" );
} );

$( "#count" ).text( "Completed tasks: " + done.length );
Try It Yourself

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();
} );
Try It Yourself

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.

🚀 Common Use Cases

  • Conditional stylingif (!$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 updatesif (!$panel.hasClass("open")) { $panel.addClass("open"); } to avoid re-triggering transitions.
  • Menu state checksif ($("nav").hasClass("mobile-open")) { ... } before closing or measuring layout.
  • Plugin initialization guardif (!$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.

📝 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.

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 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
.hasClass() Universal

Bottom line: Safe in any jQuery project. Use .hasClass() to read class state; use .addClass(), .removeClass(), or .toggleClass() to change it.

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.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about .hasClass()

Read class state — returns Boolean.

5
Core concepts
1 02

One name

Per call

Syntax
any 03

Any match

In set

Behavior
.is() 04

Selector

Compare

Compare
1.2 05

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>.

Next: .removeClass()

Learn how to strip one, several, or all CSS classes from elements.

.removeClass() 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.

6 people found this page helpful