/

How to Remove a Class from a DOM Element

How to Remove a Class from a DOM Element

Tags: JavaScript, DOM manipulation, class removal

TL;DR: Use the remove() method on the element.classList to remove a class from a DOM element.

When working with a DOM element reference, you may need to remove a class from it. This can be achieved using the remove method provided by the classList property of the element.

To remove a class, follow the syntax:

1
element.classList.remove('myclass')

Similarly, if you want to add a new class to the element, you can use the add method:

1
element.classList.add('myclass')

It’s important to note that classList is not an array, but rather a collection of type DOMTokenList. This collection provides various methods to manipulate the classes of the element.

Keep in mind that the classList property is read-only, meaning you can’t directly edit its values. However, you can use its provided methods, such as remove and add, to modify the element’s classes.

By leveraging the remove() method of element.classList, you can easily remove unwanted classes from a DOM element in your JavaScript code.