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>
Note : You can find more similar articles at - jQuery Tutorials