how to add or remove class using jquery

Last updated:23rd Apr 2022

In this post, learn how can you add or remove a CSS class in Jquery. you can easily add or remove a class by clicking on the same button.

add or remove CSS class in jquery

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src=""></script>
 .mystyle {
  padding: 30px;
  background-color: red;
  border: 1px solid green;
  font-size: 20px;

<p>Click the "clickme" button to remove the "mystyle" class from the div element which contain id mydiv:</p>

<button id="clickme">click me</button>

<div id="mydiv">
This is a DIV element.
 $(document).ready(function() {
   $("#clickme").click(function() {
      else {
Run now

Explanation for adding or remove class

  • when you click on the 'click me' button, the jquery code will get executed.
  • in jquery, It will check whether mystyle a class is present or not. i.e if($("#mydiv").hasClass("mystyle")).
  • if mystyle class is present then it will remove class by using code, $("#mydiv").removeClass("mystyle");.
  • if a class is not present then else part will get executed and mystyle class will get added. $("#mydiv").addClass("mystyle");.