jQuery

jQuery Check Class Examples

Do you wish to check if element has Class using jQuery but do not know where to begin? Worry no more! In this article, I am going to share a very easy and efficient way to check if any desired element has a specific class or not using jQuery. Read on to find out more.

How to use jQuery Check Class

Let’s assume that we got couple of divs and they have id’s and classes assigned to them. In order to check class of the div, we can use a simple method called hasClass. The following is the full source code of a working example:

Example to Check if element has Class using jQuery

<html>
<head>
<title>jQuery check if element has class</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>

<body>

<div id="mydiv1" class="my_class1">This is my 1 div</div>

<div id="mydiv2" class="my_class2">This is my 2 div</div>
<script type="text/javascript" language="javascript" >

$(document).ready(function(){

//The first div has the my_class1 applied to it, so the following will alert true
alert( $('#mydiv1').hasClass('my_class1') );

//The second div does NOT have the my_class345 applied to it, so the following will alert false
alert( $('#mydiv2').hasClass('my_class345') );

});

</script>
</body>
</html>

When you run the above code, you should be able to see 2 alerts. The first one would alert true & the second one would alert false. I have left comments above the relevant lines in the source code for your guidance.

Don’t you think it’s simple?

Do you know of any other ways to check if an element has a specific class or not using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*