How to add or remove CSS class in JavaScript when click on button

Last updated:26th Apr 2022

In this post, learn how can you add or remove a CSS class for a live page by using javascript. you can easily add or remove a class by clicking on the same button.

HTML


<p>Click the "Clickme" button to remove the "mystyle" class from the DIV element:</p>

<button onclick="callFunction()">clickme</button>

<div id="mydiv">
Apply CSS on div tag which contain id myDiV.
</div>
 

CSS


<style>
.mystyle {
  padding: 30px;
  margin:5px;
  background-color: red;
  color:white;
  border: 1px solid green;
  font-size: 20px;
}
</style>
 

Javascript


<script>
function callFunction() {
  var element = document.getElementById("mydiv");
   if (element.classList.contains("mystyle")) {
        element.classList.remove("mystyle");
   } 
  else {
	element.classList.add("mystyle");
   } 
} 
</script>
 
Run now

when you click on a 'clickme' button, mystyle class gets added and when you click again class get remove from div element which contain id mydiv.

Output

Apply CSS on div tag which contain id mydiv.