Use jQuery’s hasClass() method to check whether an element has a particular CSS class: for example, $('#panel').hasClass('active') returns true if the selected element has the class and false if it does not. It checks class membership without changing the element.
Basic Syntax and Example
Call .hasClass(className) on a jQuery collection, passing the class name as a string. Do not include the leading dot used in a CSS selector.
if ($('#menu').hasClass('open')) {
console.log('The menu is open');
}
Here, #menu selects the element with the ID menu. The method tests whether that element’s class list includes open. This is a membership check, not a test for an exact match of the entire class attribute. An element with class="menu open highlighted" still has the class open.
Use one class name per call. To check for a class on an element selected by another selector, the same pattern applies:
$('.card').hasClass('featured')
What the Method Returns
hasClass() returns a Boolean value: true or false. That makes it suitable for an if statement, a conditional expression, or any code that needs a yes-or-no answer.
truemeans at least one element in the jQuery collection has the named class.falsemeans none of the elements in that collection has it.
The “at least one” behavior matters when a selector matches several elements. For example, if a page has ten .card elements and one has the class selected, $('.card').hasClass('selected') returns true. It does not tell you which card matched or how many cards have the class.
If you need to test one particular item in a collection, narrow the selection or use .eq(index). For example, $('.card').eq(0).hasClass('selected') tests only the first matched card. An empty jQuery collection returns false, so a missing element generally does not cause an exception with this method.
Checking Classes and Changing Them
A common use is to choose an action based on an element’s current state. For instance, a button might expand or collapse a panel:
const $panel = $('#details');
if ($panel.hasClass('expanded')) {
$panel.removeClass('expanded');
} else {
$panel.addClass('expanded');
}
If the intention is simply to switch a class on or off, jQuery also offers .toggleClass(). It can make the code shorter, but it is not always interchangeable with an explicit check: the conditional form lets you perform different actions in each state, and it can be easier to understand when other logic is involved.
Other related methods have different purposes:
.addClass('active')adds a class; it does not report whether the class was present..removeClass('active')removes a class..toggleClass('active')toggles a class on or off..is('.active')tests whether an element matches a selector. It can express more than a class check, such as a compound selector.
Choose hasClass() when the question is specifically whether a class is present. Choose is() when you need to check a broader selector condition.
Class Names, Selectors, and Timing
Pass the class name alone, without a period: hasClass('active'), not hasClass('.active'). The dot belongs to CSS selector syntax, as in $('.active') or .is('.active'). Supplying the dot to hasClass() asks for a class literally named .active, which is not the usual class name.
Class names are case-sensitive in ordinary HTML class matching, so hasClass('Active') and hasClass('active') are different checks. A class name cannot contain whitespace as one class token; whitespace separates multiple classes. To check for two classes, call the method twice:
const $item = $('#item');
const hasBoth = $item.hasClass('active') && $item.hasClass('highlighted');
Make sure the check runs after the relevant element exists and after any code that might add or remove the class. If a script runs before the page markup is available, the selector may match nothing, causing the check to return false. Put the script after the markup, or run it after the document is ready:
$(function () {
console.log($('#menu').hasClass('open'));
});
If another event handler changes the class later, checking it before that change naturally reports the earlier state. Put the check in the handler or callback where the updated state is available.
Common Mistakes and Debugging
A false result does not necessarily mean the method is broken. First confirm that the selector found the element, that the class spelling and capitalization match, and that the class has been applied by the time the check runs. You can inspect the selection’s length while debugging:
const $target = $('#menu');
console.log($target.length);
console.log($target.hasClass('open'));
A length of 0 means the selector matched no elements. Check for a misspelled ID, duplicate or unexpected markup, or code that ran too early. If the length is greater than one, remember that a true result means at least one matched element has the class, not necessarily the first one.
Also distinguish a class from other attributes. hasClass('active') does not test whether an element has an ID, a data attribute, or a particular inline style. Use the appropriate selector or attribute method for those checks. And avoid comparing the full class attribute as a string: class order can vary, and other classes may be present. Membership is exactly what hasClass() is designed to test.
jQuery and Native JavaScript
In code that already uses jQuery, hasClass() is a concise and clear option. Native JavaScript provides the equivalent class-list check through element.classList.contains('active'):
const element = document.querySelector('#menu');
const isOpen = element !== null && element.classList.contains('open');
Unlike a jQuery selection, document.querySelector() returns either one DOM element or null; calling classList.contains() on null would cause an error. The explicit null check handles the missing-element case. For multiple native elements, test each one individually, for example with document.querySelectorAll() and an iteration method.
Neither approach is universally required. Use the style already used by the surrounding code, and avoid wrapping a DOM element in jQuery solely for a one-off class check if the project otherwise uses native JavaScript. Conversely, there is no need to replace working jQuery code just to perform this simple test.
Frequently Asked Questions
Does hasClass() check every selected element?
It checks the collection and returns true if at least one matched element has the class. To inspect each element separately, iterate over the collection or select a specific one.
Can I check for two classes at once?
Pass one class name per call, then combine the Boolean results with && for both or || for either. For example, $el.hasClass('open') && $el.hasClass('visible') checks that both are present.
Should the class name include a dot?
No. Write hasClass('active'). A leading dot is used when writing a CSS selector, such as $('.active').
What happens if the selector finds no element?
The resulting jQuery collection is empty, and hasClass() returns false. If you need to distinguish “element missing” from “element present without this class,” check the collection’s length.
Can I use hasClass() to toggle a class?
You can check first and then call addClass() or removeClass(). If you only need to invert the class state, toggleClass() is usually more direct.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Live-Action Remakes: The Good, the Bad, and Why
- Ryobi Tools Under $40 Worth Buying
- On the Inside Jordan? Meaning and Context
- Why AI Art Often Looks Unconvincing
- AI Is Making Our Lives Easier? The Real Answer
- Unusual Things Inspired by Twin Peaks