Main Tutorials

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>

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
Rich
10 years ago

Very helpful! Thank you!

john
10 years ago

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