Borislav Hadzhiev
Fri Dec 31 2021·2 min read
Photo by Tony Pham
To remove a class from multiple elements:
document.querySelectorAll
method to select the elements.forEach()
method to iterate over the collection.classList.remove()
method to remove the class from each element.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box big">Box 1</div> <div class="box big">Box 2</div> <div class="box big">Box 3</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const boxes = document.querySelectorAll('.box'); boxes.forEach(box => { // ✅ Remove class from each element box.classList.remove('big'); // ✅ Add class to each element // box.classList.add('small'); });
We used the
document.querySelectorAll
method to select all DOM elements with a class of box
.
Note that if you use another method, e.g.
document.getElementsByClassName,
you might have to convert the return value to an array before calling the
forEach()
method.
const boxes = Array.from(document.getElementsByClassName('box')); boxes.forEach(box => { // ✅ Remove class from each element box.classList.remove('big'); // ✅ Add class to each element // box.classList.add('small'); });
The function we passed to the forEach
method gets called with each element in
the array.
On each iteration, we used the classList.remove() method to remove a class from the element.
Note that you can pass as many classes as necessary to the classList.remove()
method.
const boxes = Array.from(document.getElementsByClassName('box')); boxes.forEach(box => { // ✅ Remove class from each element box.classList.remove('big', 'medium', 'large'); });
If any of the provided class names are not present on the element, the
remove()
method ignores them and no error is thrown.
If you need to add a class to each element in the collection, you can use the classList.add() method.
const boxes = Array.from(document.getElementsByClassName('box')); boxes.forEach(box => { // ✅ Remove class from each element box.classList.remove('big'); // ✅ Add class to each element box.classList.add('small'); });
If the elements you are removing a class from have different identifiers, e.g.
class names, ids, etc, you can pass multiple comma-separated selectors to the
querySelectorAll
method.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box1 big">Box 1</div> <div class="box2 big">Box 2</div> <div class="box3 big">Box 3</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const boxes = document.querySelectorAll('.box1, .box2, .box3'); boxes.forEach(box => { box.classList.remove('big'); });
We selected the elements with classes box1
, box2
and box3
and removed a
class from each element in the collection.
document.querySelectorAll
method.