How to Remove a Class from an Element

A quick guide on how to remove a CSS class from an HTML element in TypeScript using the classList.remove() method.

When you are changing the style of an element, you often need to remove a CSS class. The classList property on an element makes this easy.

A common use case is to have a utility class that hides an element, and then remove that class to make it appear.

HTML
<div id="my-element" class="hidden">
    <p>Some content</p>
</div>

<style>
    .hidden {
        display: none;
    }
</style>

To make the element visible, you can select it and then use the classList.remove() method.

TypeScript
const myElement = document.querySelector<HTMLDivElement>("#my-element");

if (myElement) {
    // Remove the 'hidden' class
    myElement.classList.remove("hidden");
}

After this code runs, the <div> will no longer have display: none; and will be visible on the page.

How it works:

  1. myElement.classList: This property returns a live collection of all the classes on the element. It’s not just a string, but a special object with helpful methods.
  2. .remove("hidden"): This is one of the methods on classList. It looks for the “hidden” class and removes it. If the class doesn’t exist on the element, it doesn’t do anything and doesn’t cause an error.

You can also remove multiple classes at once by passing more arguments:

TypeScript
myElement.classList.remove("class1", "class2");

Other recipes in DOM