Home > Web Front-end > CSS Tutorial > How to Remove a CSS Class from an Element Using Native JavaScript?

How to Remove a CSS Class from an Element Using Native JavaScript?

DDD
Release: 2024-12-28 19:49:17
Original
1020 people have browsed it

How to Remove a CSS Class from an Element Using Native JavaScript?

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');
Copy after login

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');
};
Copy after login

HTML:

<div>
Copy after login

CSS:

.red {
  background: red;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template