Remove all Classes from an Element using JavaScript

avatar

Borislav Hadzhiev

Sat Jan 01 20222 min read

banner

Photo by Brooke Cagle

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 of 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 classNameproperty 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 does not 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 and easier to read.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee