Learn html, css, javascript online and how to make a webpage design

How to add class and remove class in javascript?

Thursday 7th of January 2021 03:35:21 PMJavascript

When programming a website, sometimes we will need to change the classname of an element in order to animate a predefined in CSS. So how to add or delete an existing class on an element? Very simple, you see the example below:

Using .classList.add to add classname with javascript

<!DOCTYPE html>
<html>
<head>
    <title>How to add class and remove class in javascript? - HtmlcssDownload.com</title>
    <style>
       .text-red{color:#f00;}
    </style>
</head>
<body>
  <div id="myElement"></div>
  <button onclick="addClassName()">Add Class</button>
<script>
    function addClassName(){
       var myElement = document.getElementById("myElement");
       myElement.classList.add("text-red");
    }
  
</script>
  
</body>
</html>

 

Using .classList.remove to remove classname with javascript

<!DOCTYPE html>
<html>
<head>
    <title>How to add class and remove class in javascript? - HtmlcssDownload.com</title>
    <style>
       .text-red{color:#f00;}
    </style>
</head>
<body>
  <div id="myElement"></div>
  <button class="text-red" onclick="removeClassName()">Remove Class</button>
<script>
    function removeClassName(){
       var myElement = document.getElementById("myElement");
       myElement.classList.remove("text-red");
    }
  
</script>
  
</body>
</html>

 

 

We are Recommending you: