jQuery

jQuery hasClass method Examples

Did you want to check if a div or any other element has a certain class? Now you can easily check if a div has a specific class, with just 1 line of code using the jQuery hasClass method. Read on to find out more.

How to use .hasClass() method in jQuery

Let’s see how to use the hasClass() method by means of a simple example. The following is the HTML source code along with the jQuery source code of the example:

Example of ussing the .hasClass() method in jQuery

<html>
<head>
<title>Check if div hasClass</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>

<body>
<div id="my_div" class="my_class">Some content in the div.</div>

<button id="check">Check</button>

<script type="text/javascript">

$(document).ready(function() {

$("#check").click( function() {

alert( $("#my_div").hasClass("my_class") );

});

});

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

Once the page has loaded, simply click on the “Check” button to see if the desired element (in this case, the div) has the required class. If yes, then we see a JavaScript alert that says “true”. If you mention a non-existing class in the hasClass method, you will see “false” in the alert. You may modify this to suit your needs.

Your Turn!

Do you know of any other ways to use hasClass in jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*