How to Check if an Element Has a Class in jQuery
Checking whether an HTML element possesses a specific CSS class is a
common task in front-end development. In jQuery, this is most
efficiently accomplished using the built-in .hasClass()
method, which inspects the target element and returns a boolean value
(true or false). This guide covers how to use
.hasClass(), alternative approaches like the
.is() method, and how to handle class checks within event
listeners.
The .hasClass() Method
The primary and most performant way to verify a class in jQuery is
the .hasClass() method. It takes a single string parameter
representing the class name. Do not include a preceding dot
(.) in the argument.
if ($('#myElement').hasClass('active')) {
// Code to run if the element has the "active" class
console.log('Element has the class!');
} else {
// Code to run if the element does not have the class
console.log('Element does not have the class.');
}If your jQuery selector matches multiple elements,
.hasClass() returns true if at least
one of the matched elements has the specified class.
The .is() Method
An alternative approach is using the .is() method. This
method checks the selected element against a CSS selector, element, or
jQuery object. Because it takes a CSS selector, you must include the dot
(.) before the class name.
if ($('#myElement').is('.active')) {
console.log('Element matches the selector .active');
}While .is() provides more flexibility by allowing you to
test for multiple conditions, pseudo-selectors (like
:visible), or attributes, .hasClass() is
faster and more semantic for simple class checks.
Checking Classes Inside Event Handlers
When handling user interactions, you often need to check the class of
the element that triggered the event. You can wrap this in
a jQuery object to check its class immediately:
$('.btn').on('click', function() {
if ($(this).hasClass('disabled')) {
console.log('Button is disabled. Action cancelled.');
return false;
}
console.log('Button clicked successfully.');
});Vanilla JavaScript Alternative
If you want to perform this check without relying on jQuery, modern
browsers provide the native classList.contains()
property:
const element = document.querySelector('#myElement');
if (element.classList.contains('active')) {
console.log('Element has the class using native JavaScript.');
}