How To Remove Class In Javascript

Working with HTML classes is a common task when developing web applications. You often need to add, remove,
or toggle classes to manipulate the appearance and behavior of elements on the page. In this blog post, we will
discuss how to remove a class from an HTML element using JavaScript.

Using the classList property

The easiest way to work with classes in JavaScript is to use the classList property. It
provides a convenient and efficient way to access and manipulate the list of classes for an element. To remove a
class from an element using the classList property, you can use the remove()
method.

    const element = document.querySelector('.my-element');
    element.classList.remove('my-class');
    

In the example above, we first select the element with the class my-element using the
querySelector() method. Then, we remove the class my-class from the element
using the remove() method of the classList property.

Using the className property

Another way to remove a class from an element is by using the className property. This
property represents the class attribute of an element as a string. You can manipulate this string to add or
remove classes.

    const element = document.querySelector('.my-element');
    const classArray = element.className.split(' ');
    const index = classArray.indexOf('my-class');

    if (index !== -1) {
        classArray.splice(index, 1);
        element.className = classArray.join(' ');
    }
    

In this example, we first select the element with the class my-element using the
querySelector() method. Next, we convert the className string into an array
of classes using the split() method. We then find the index of the class
my-class in the array using the indexOf() method. If the class is found in
the array (index is not -1), we remove it using the splice() method and update the
className property with the modified array of classes.

Conclusion

Removing a class from an HTML element is a common task in web development, and JavaScript provides several ways
to do so. The most convenient and recommended approach is to use the classList property and its
remove() method. However, if you need more control over the class attribute or need to support
older browsers, you can use the className property and manipulate the class string.