jQuery toggleClass example

The toggleClass() method means if matched elements do not have the class name, then add it; if matched elements already have the class name, then remove it.

Let see an example, a simple ‘p’ tag.


<p>This is paragraph</p>

Call $(‘p’).toggleClass(‘highlight’), it will add a highlight class to the ‘p’ tag.


<p class="highlight">This is paragraph</p>

Call $(‘p’).toggleClass(‘highlight’) again, it will remove the highlight class from the ‘p’ tag.


<p>This is paragraph</p>

The toggleClass() is equivalent to the following jQuery codes as well.


if ($('p').is('.highlight')) {
    $('p').removeClass('highlight');
}
else{
    $('p').addClass('highlight');
}

jQuery toggleClass example


<html>
<head>
<style type="text/css">
  .highlight { 
  	background:blue;
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery toggleClass example</h1>
	
  <p>This is paragraph1</p>
  <p id="para2">This is paragraph2 (toggleClass effect)</p>
  <p>This is paragraph3</p>
  <p id="para4">This is paragraph4 (add/remove effect)</p>
  
  <button id="toggleClass">toggle class</button>
  <button id="addremoveClass">Add/Remove class</button>
  
<script type="text/javascript">
	
    $("#toggleClass").click(function () {
		
	  $('#para2').toggleClass('highlight');
	  
    });
	
    $("#addremoveClass").click(function () {
		
	  if ($('#para4').is('.highlight')) {
	  	
	      $('#para4').removeClass('highlight');
		
	  }
	  else{
	  	
	      $('#para4').addClass('highlight');
	  
	  }

    });
	
</script>
</body>
</html>

2 comments on “jQuery toggleClass example

  1. Hi there mates, its fantastic piece of writing concerning cultureand completely defined, keep
    it up all the time.

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *