Remove all Classes from an Element using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 26, 2022

banner

Photo from Unsplash

Remove all Classes from an Element using JavaScript #

To remove all classes from an element, set the element's className property to an empty string, e.g. box.className = ''. Setting the element's className property to an empty string empties 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> .bg-salmon { background-color: salmon; } .text-white { color: white; } </style> </head> <body> <div id="box" class="text-white bg-salmon">Box 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // ✅ Remove all classes from element box.className = '';

The className property can be used to read, set or update the value of the element's class attribute.

When the property is set to an empty string, the attribute remains on the element but is empty - all the element's classes get removed.

An alternative approach is to use the Element.removeAttribute() method.

To remove all classes from an element, use the removeAttribute() method, e.g. box.removeAttribute('class'). The method removes will remove the class attribute from the element, effectively removing all of the element's classes.

index.js
const box = document.getElementById('box'); // ✅ Remove all classes from element box.removeAttribute('class');
The difference between the two approaches is that when we set the className property of the element to an empty string, the class attribute remains on the element without a value.

The removeAttribute method simply removes the class attribute from the element.

If the element doesn't have a class attribute set, the removeAttribute method will not throw an error, it will simply return an undefined value.

Which approach you pick is a matter of personal preference. I'd go with setting the className property to an empty string, as I find it more direct.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.