How to remove class name from element using JavaScript

← PrevNext →

You can use the remove() method of "classList" property in JavaScript to remove class name from an element dynamically. I have previously shared an example where I have used the "classList" property to change class name of an element dynamically in JavaScript.

Here's an example.

I have a DIV element, which has two classes assigned and I'll remove one of the class with the click of a button.

<style>
  * { font-family: Corbel;}
  
  input, p { font-size: 18px; }
  .intro {
    color: #fff;
    padding: 10px;
    background-color: red;
  }
  .g1::before {
    content: 'Hello :-) ';
  }
</style>
<body>
  <!--   this DIV has 2 classes assigned. -->
  <div id='dv' class='intro g1'>
      I am Arun Banik
  </div>
  
  <p>
    <input type='button' value='Click to remove class attribute' id='bt'>
  </p>
</body>

<script>
  window.addEventListener('click', function (e) {
    if (e.target.id === 'bt') {
      document.getElementById('dv').classList.remove('intro');   // remove class name "intro" from the element.
    }
  });
</script>
Try it

Related Article

How to remove multiple class names from an element with the click of a button using jQuery?

The .remove() method takes a parameter. In the above example, I have passed the class name "intro" as a parameter to the method to remove the class from the element.

However, if you noticed, the DIV element has two different class names defined (intro and g1). You can remove multiple class names using the ".remove()" method. All you have to do is, seperate the class names using a "comma". Like this...

<script>
  window.addEventListener('click', function (e) {
    if (e.target.id === 'bt') {
      // remove multiple class names from the element.
      document.getElementById('dv').classList.remove('intro', 'g1');   
    }
  });
</script>
Try it

Happy coding. 🙂

← PreviousNext →