How to Remove a Class from an Element With Vanilla JavaScript

Removing a class from an HTML element is simple with the JavaScript classList property’s remove() method. If you’ve read How to add a class to an element already then you’ll realize that removing a class is the exact same way, just in reverse.

Let’s look at the generic classList.remove() formula first — and then follow up with a practical example.

The formula

var element = document.querySelector("selector")
element.classList.remove("class")
We find the target element, then we remove a specified class from this element.

In the generic example above, we find the first HTML element on a page with the specified selector name (it could be an element selector, class selector, etc.) and store a reference to it with a variable.

Then we attach the classList property’s remove() method to the element object (the variable) and specify the class we want to remove from it.

Practical classList.remove() example

To find and remove a class, we obviously need to find an element that has a class.

So what class should we remove?

To make our life easier, I just added a class called italic to the paragraph you’re reading. As you can see, it makes the text italicized.

Let’s “un-italicize” the paragraph above with our newfound classList.remove technique:

var firstParagraph = document.querySelector(".italic")
firstParagraph.classList.remove("italic")
Add this to your browser Console and hit enter.

And the result:

Removing the italic class from the paragraph element, using the JavaScript classList.remove method.

Note: I have the italic class in my website’s CSS stylesheet, that’s why it works. The class looks like this:

.italic {
  font-style: italic;
}

Resources


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on