To check if an element has class using jQuery, the simplest way is to use the hasClass() method.
$('#element').hasClass('example-class');
Let’s say I have the following HTML:
This is a div we will check.
If we want to check the div to see if it has the class “check-me”, we can do the following:
var hasClassCheckMe = $('#div-to-check').hasClass('check-me');
console.log(hasClassCheckMe); // true
If you are using WordPress, don’t forget to change the $ to jQuery as below:
var hasClassCheckMe = jQuery('#div-to-check').hasClass('check-me');
console.log(hasClassCheckMe); // true
Checking if Element Has Class Using jQuery On Click
We can check if a HTML element has a class on click using jQuery very easily by combining the hasClass() method with a click event.
Let’s say we have the following HTML code and we want to display if our div has the class “check-me” and “check-me-too” in the span below:
We will check this div for class "check-me"
Does the div "div-to-check" have class "check-me"? .
Does the div "div-to-check" have class "check-me-too"? .
Check
We can utilize both the jQuery click() method and jQuery hasClass() method to find if the div has class “check-me”. Then we will change the text of the span and display true or false.
Below is the JavaScript code which will allow us to see if our element has the class “check-me” and “check-me-too” then display the two values.
$('#click-me').click(function(){
$("#hasClass-value-1").text($('#div-to-check').hasClass('check-me'));
$("#hasClass-value-2").text($('#div-to-check').hasClass('check-me-too'));
});
The final code and output for this example of how to check if an element has a class on a click using jQuery and JavaScript is below:
Code Output:
Does the div “div-to-check” have class “check-me”? .
Does the div “div-to-check” have class “check-me-too”? .
Full Code:
We will check this div for class "check-me"
Does the div "div-to-check" have class "check-me"? .
Does the div "div-to-check" have class "check-me-too"? .
Check
Hopefully this article has been useful for you to understand how to use jQuery to check if an element has a certain class.