Borislav Hadzhiev
Last updated: Dec 31, 2021
Check out my new book
Use the classList.remove()
method to remove a class from a div
element,
e.g. box.classList.remove('my-class')
. The remove()
method takes one or more
classes as parameters and removes the classes from the element's class list.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body> <div class="box salmon">Box 1</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const box = document.querySelector('.box'); // ✅ Remove class box.classList.remove('salmon'); // ✅ Add class // box.classList.add('my-class');
We selected the element using the document.querySelector()
method.
We then used the
classList.remove
method to remove the salmon
class from the div
element.
classList.remove()
method can be used to remove classes from any type of element, not just a div
.Note that you can pass as many classes as necessary to the remove()
method.
const box = document.querySelector('.box'); box.classList.remove( 'salmon', 'text-white', 'third-class' );
If any of the classes is not present on the element, the remove()
method
ignores the class and does not throw an error.
Conversely, you can add a class to a div
element, by calling the
classList.add()
method on the element.
const box = document.querySelector('.box'); box.classList.add( 'first-class', 'second-class', 'third-class' );
If you need to remove one or more classes from multiple elements:
querySelectorAll()
method.forEach()
method to iterate over the collection of elements.classList.remove()
method on each element.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body> <div class="box salmon">Box 1</div> <div class="box salmon">Box 2</div> <div class="box salmon">Box 3</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const boxes = Array.from(document.querySelectorAll('.box')); boxes.forEach(box => { box.classList.remove('salmon'); });
We used the document.querySelectorAll()
method to select all of the DOM
elements that have a class of box
.
We used the forEach()
method to iterate over the collection of elements and
called the remove()
method on each element.