jQuery CSS Classes


In jQuery, there are four types of jQuery methods that are used to manipulate the CSS classes assigned to the HTML element.

jQuery addClass() Method

The jQuery addClass() method is used to add one or more classes to the specified elements.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#data").addClass("myClass"); 
  });
});
</script>
</head>
<body>
 <div id="data">
   <p>This is paragarph tag.</p>
   <b>This is bold tag.</b>
  </div>
  <button>Click here</button>
</body>
</html>

jQuery removeClass() Method

The jQuery removeClass() method is used to remove the class from the specified elements.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#data").removeClass("myclass"); 
  });
});
</script>
</head>
<body>
 <div id="data" class="myclass">
   <p>This is paragarph tag.</p>
   <b>This is bold tag.</b>
  </div>
  <button>Click here</button>
</body>
</html>

jQuery toggleClass() Method

The jQuery toggleClass() method is used to add or remove the class of the specified elements. such as if you have a class on the elements, then it will remove the class and do not have a class on the elements, then it will add the class.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#data").toggleClass("myclass"); 
  });
});
</script>
</head>
<body>
 <div id="data">
   <p>This is paragarph tag.</p>
   <b>This is bold tag.</b>
  </div>
  <button>Click here</button>
</body>
</html>