Computer >> Computer tutorials >  >> Programming >> Javascript

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")

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")

And the result:

How to Remove a Class from an Element With Vanilla JavaScript

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

  • MDN Web Docs element.classList