Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsiTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Use jQuery’s .hasClass() method and pass the class name without a leading dot:
if ($('#myElement').hasClass('active')) {
// The selected element has the active class
}
Check whether a jQuery selection has a class
.hasClass() returns true if at least one element in the selected jQuery collection has the specified class; otherwise it returns false.
const hasActiveClass = $('#myElement').hasClass('active');
if (hasActiveClass) {
// Run code when the element has the active class
}
Provide the class name as a string, such as 'active', not a CSS selector such as '.active'. You can use the returned boolean directly in an if condition or store it in a variable.
Free tools Windows power users keep installed
One-click scans. No signup required.
Check a selected element or a group
One element
When the selector matches one element, the result tells you whether that element has the class:
#1 Best Overall
- Brand: Wiley
- Set of 2 Volumes
- A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
if ($('#menu').hasClass('open')) {
$('#menu').hide();
}
Multiple elements
If the jQuery selection contains multiple elements, .hasClass() returns true when any one of them has the class. It does not mean that every selected element has it:
if ($('.menu-item').hasClass('selected')) {
// At least one .menu-item is selected
}
To test each element individually, iterate over the selection:
Rank #2
- JavaScript Jquery
- Introduces core programming concepts in JavaScript and jQuery
- Uses clear descriptions, inspiring examples, and easy-to-follow diagrams
$('.menu-item').each(function () {
if ($(this).hasClass('selected')) {
// This particular element has the selected class
}
});
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Handle a selection that matches nothing
A selector that matches no elements produces an empty jQuery collection, and .hasClass() returns false for it. This lets the condition safely fail without first checking whether the selection exists:
Recommended Free Tools
Quick Recap
Best Value
if ($('#missingElement').hasClass('active')) {
// This block will not run when no element matches
}
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

