jQuery hasClass()
The jQuery hasClass()
method is used to check if an element has a specified class. It returns a boolean value (true
or false
) based on whether or not the element has the class.
Syntax
$(selector).hasClass(classname)
selector
: The element(s) to check for the specified class.classname
: The name of the class to check for.
Use
The hasClass()
method is useful for adding conditional logic to your jQuery code based on whether or not an element has a particular class. For example, you might want to toggle a class on/off based on whether or not an element has a certain class.
Example
Consider the following HTML code:
<div id="item" class="active">This is a div.</div>
To check if the element with id="item"
has the class "active" using hasClass()
, we can use the following jQuery code:
if ($('#item').hasClass('active')) {
console.log('The item is active.');
} else {
console.log('The item is not active.');
}