Main Tutorials

How to check if an element has a certain class name with jQuery

jQuery comes with two methods to check if an element has a certain class name. Both methods have the same functionality.

  1. is(‘.classname’)
  2. hasClass(‘.classname’)

For example, to check if div element has a class name of ‘redColor’.

1. is(‘.classname’)


$('div').is('.redColor')

2. hasClass(‘.classname’)


$('div').hasClass('.redColor')

Example

If the div element has a class name of ‘redColor’, then change its class to ‘blueColor’.


<html>
<head>
<style type="text/css">
  .redColor { 
  	background:red;
  }
  .blueColor { 
  	background:blue;
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery check if an element has a certain class</h1>

  <div class="redColor">This is a div tag with class name of "redColor"</div>
  
  <p>
  <button id="isTest">is('.redColor')</button>
  <button id="hasClassTest">hasClass('.redColor')</button>
  <button id="reset">reset</button>
  </p>
<script type="text/javascript">
	
    $("#isTest").click(function () {
		
	  if($('div').is('.redColor')){
	  	$('div').addClass('blueColor');
	  }
	  
    });
	
    $("#hasClassTest").click(function () {
		
	  if($('div').hasClass('.redColor')){
	  	$('div').addClass('blueColor');
	  }
	  
    });
	
	$("#reset").click(function () {
	  location.reload();
    });
	
	
</script>
</body>
</html>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
webster
11 years ago

classname should be without dot for hasClass function.

$('div').hasClass('redColor')
Alex Shulz
9 years ago
Reply to  webster

great! yousaved my night!