How to Remove class if it exists on Element using JavaScript

To remove a class from an HTML element using JavaScript, you can use the classList property, which provides methods for manipulating the classes of an element. Specifically, you can use classList.remove() to remove a class if it exists.

Here’s an example of how to do this:

// Select the element
const element = document.querySelector(".your-element-class");

// Check if the class exists and remove it
if (element.classList.contains("class-to-remove")) {
    element.classList.remove("class-to-remove");
}

Explanation:


Call “classList.remove()” directly:

You can also directly call classList.remove() without checking if the class exists, as it will not throw an error if the class is not present:

element.classList.remove("class-to-remove");

This line will simply remove the class if it exists and do nothing if it doesn’t, making it a concise option.