Remove all Classes except One using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 1, 2022

banner

Photo from Unsplash

Remove all Classes except One using JavaScript #

To remove all classes from an element except one, use the className property on the element to set its class string to the class you want to keep, e.g. box.className = 'bg-yellow'. The className property can be used to read, set or update the class of the DOM element.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .bg-yellow { background-color: yellow; } .text-red { color: red; } .big { padding: 20px; } </style> </head> <body> <div id="box" class="bg-yellow text-red big">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 except bg-yellow box.className = 'bg-yellow';

We used the document.getElementById() method to select the element by its id.

We then set the element's className property to the only class we want to keep.

An alternative approach which achieves the same result is to use the setAttribute() method.

index.js
const box = document.getElementById('box'); box.setAttribute('class', 'bg-yellow');

The setAttribute method sets the value of an attribute on the specified element.

If the attribute already exists on the element, its value is updated, otherwise a new attribute is added with the specified name and value.

When we use the setAttribute method on an element that already has a class attribute, we are effectively replacing the value of the element's class.

An alternative and more manual approach to remove all classes from an element except one is to use the classList.remove() method.

index.js
const box = document.getElementById('box'); box.classList.remove('text-red', 'big');

The remove() method takes one or more class names as parameters and removes the classes from the element.

If the class does not exist on the element, the remove() method does not throw an error, it just ignores the class.

Which approach you pick is a matter of personal preference. I'd go with the approach that sets the className property on the element to the class I want to keep, because it's the most direct and easiest to read of the 3.
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.