Example to show how to add / remove CSS class dynamically with jQuery.

Query comes with two methods to check if an element has a certain class name. Both methods have the same functionality.
  • $(selector).is(‘.classname’)
  • $(selector).hasClass(‘classname’)

Example: check if UL with LI id='li1' element has a class name of ‘active’.

$(selector).is(‘.classname’)

$('#li1').is('.active')

$(selector).hasClass(‘classname’)

$('li1').hasClass('active')

Example

If the div element has a class name of ‘highlightYellow’, then change its class to ‘highlightGreen’.
<html>
<head>
<style type="text/css">
.highlightYellow {
  background:#FFFF80;
}
.highlightGreen {
  background:#80FF80;
}
</style>
<script type="text/javascript"
    src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js">
</script>
</head>
<body>
<h1>jQuery check if an element has a certain class</h1>
<div class="highlightYellow">
    This is a div tag with class name of "highlightYellow"
</div>
  
<div><button id="isTest">is('.highlightYellow')</button>
    <button id="hasClassTest">hasClass('highlightYellow')</button>
    <button id="reset">reset</button></div>
<script type="text/javascript">
$(function(){
  $("#isTest").click(function () {
	  if($('div').is('.highlightYellow')){
	  	$('div').addClass('highlightGreen');
	  }
  });

  $("#hasClassTest").click(function () {
	 if($('div').hasClass('highlightYellow')){
	  	$('div').addClass('highlightGreen');
	 }
  });

  $("#reset").click(function () {
      $('#myDIV').removeClass('highlightGreen').addClass('highlightYellow');
  });
});
</script>
</body>
</html>

jQuery check if an element has a certain class

This is a div tag with class name of "highlightYellow" and id='myDIV'