Remove a class from a Div element using JavaScript

avatar

Borislav Hadzhiev

Last updated: Dec 31, 2021

banner

Check out my new book

Remove a class from a Div element using JavaScript #

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.

index.html
<!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.

index.js
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.

The 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.

index.js
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.

index.js
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:

  1. Select the elements using the querySelectorAll() method.
  2. Use the forEach() method to iterate over the collection of elements.
  3. Call the classList.remove() method on each element.
index.html
<!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.

index.js
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.

Use the search field on my Home Page to filter through my more than 3,000 articles.