How to remove a class from all elements in JavaScript

how to remove a class from all elements using JavaScript

Posted by Ervin Adams on August 8, 2022

How to remove a class from all elements in JavaScript

how to remove a class from all elements using JavaScript

Posted by Ervin Adams on August 8, 2022

Let us look at how you can remove a class from all elements using JavaScript.

Step 1. Create a consistent class that will not be removed on all the elements 

Step 2. Create the class to be removed from all the elements

Step 3 Use document.querySelectorAll() to select the elements with the 2 classes

Step 4. Use the forEach() method to loop through all the elements

Step 5. Use the classList.remove() method within the forEach() method to remove the class from each element

CSS

.txt {
  font-size: 14px;
}
        
.txt-clr {
  color: #fc03db;
}

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 remove a class from all elements in JavaScript</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container">
        <div class="col-9 pt-5 mx-auto">
            <div class="txt txt-clr">Lemon</div>
            <div class="txt txt-clr">Orange</div>
            <div class="txt txt-clr">Lime</div>
            <div class="txt txt-clr">Grape</div>
        </div>
    </div>
  </main>
</body>
</html>

JS

const allElements = document.querySelectorAll('.txt.txt-clr');

allElements.forEach(el => {
  el.classList.remove('txt-clr');
});

Or

To identify the class to be removed, use document.getElementsByClassName() method within the Array.from() method converting the object to an array, then loop.

JS

const allElement = Array.from(document.getElementsByClassName('txt-clr'));

allElement.forEach(el => {
  el.classList.remove('txt-clr');
});