Home >Web Front-end >CSS Tutorial >How to Remove a CSS Class Using Vanilla JavaScript?
Remove CSS Class: A Comprehensive JavaScript Guide
Removing a CSS class from an element using vanilla JavaScript is a common task encountered by web developers. Unlike jQuery, which provides a simplified API, JavaScript offers a versatile and low-level approach to this operation.
To effectively remove a CSS class, the preferred and standardized technique is to leverage the classList property. Supported across modern browsers, it enables precise class manipulation.
SOLUTION
The following snippet demonstrates the proper syntax:
ELEMENT.classList.remove("CLASS_NAME");
This code snippet removes the specified class (CLASS_NAME) from the target element (ELEMENT).
EXAMPLE
Consider the following example, where we have a button that toggles the removal of the "red" class from a div:
remove.onclick = () => { const el = document.querySelector('#el'); el.classList.remove("red"); };
.red { background: red }
<div>
Upon clicking the "Remove Class" button, the "red" background will be removed from the div.
Understanding how to remove CSS classes with JavaScript is crucial for maintaining a dynamic web page with precise control over element styles.
The above is the detailed content of How to Remove a CSS Class Using Vanilla JavaScript?. For more information, please follow other related articles on the PHP Chinese website!