How to Use the jQuery hasClass() Method
The jQuery hasClass()
method checks if an element contains a particular word/value in the class attribute. It will return true
if a class name is found and false
if not.
<div id="bar" class="active"></div>
$result = $('#bar').hasClass('active');
console.log($result);
true
If Element has a Class Do This
Let's use the hasClass()
method with an if statement to do something if an element has a class.
<div id="bar" class="active"></div>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
if ($('#bar').hasClass('active')) {
console.log('Has class do something...');
} else {
console.log('No class found do something else...');
}
});
If Element Doesn't Have a Class
We can use an !
(exclamation mark) to switch the polarity of an if
statement to check if an element doesn't have a class like this:
<div id="bar" class="active"></div>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
if (! $('#bar').hasClass('thing')) {
console.log('No class found do something ...');
}
});
No class found do something ...
If an Element has Multiple Classes
We can check if an element has multiple classes by supplying a space-separated list of class names inside the hasClass()
method.
<div id="bar" class="active inline"></div>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
if ($('#bar').hasClass('active inline')) {
console.log('Has classes do something...');
} else {
console.log('Not found do something else...');
}
});
Has classes do something...
In the above example, the classes have to be in the same order. If you don't know the order of the classes you could chain hasClass()
methods together:
<div id="bar" class="inline thing active"></div>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
if ($('#bar').hasClass('active') && $('#bar').hasClass('inline')) {
console.log('Has classes do something...');
} else {
console.log('Not found do something else...');
}
});
Has classes do something...
jquery