Removing CSS Class from Element with Native JavaScript
Removing a CSS class from an HTML element using JavaScript can be achieved without relying on third-party libraries like jQuery. Below are step-by-step instructions:
1. Identify the Target Element:
Use the document.querySelector() method to select the HTML element from which you want to remove the class. Specify the element's ID or another unique identifier.
2. Use the classList Property:
Modern browsers support the classList property on every element. This property represents a list of CSS classes applied to the element.
3. Remove the Class:
To remove a class, simply use the classList.remove() method and pass the class name as an argument. For example:
const element = document.querySelector('#element'); element.classList.remove('red');
Example:
The following code snippet demonstrates how to remove the "red" CSS class from an element in a practical scenario:
const button = document.querySelector('#remove'); const element = document.querySelector('#el'); button.onclick = () => { element.classList.remove('red'); };
HTML:
<div>
CSS:
.red { background: red; }
When the "Remove Class" button is clicked, the "red" CSS class will be removed from the element, changing its background color to the default.
The above is the detailed content of How to Remove a CSS Class from an Element Using Native JavaScript?. For more information, please follow other related articles on the PHP Chinese website!