Home >Web Front-end >CSS Tutorial >How Can I Remove CSS Classes from Elements Using Pure JavaScript?

How Can I Remove CSS Classes from Elements Using Pure JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 07:05:09656browse

How Can I Remove CSS Classes from Elements Using Pure JavaScript?

Eliminate CSS Classes from Elements with Pure JavaScript

In the realm of web development, the task of removing CSS classes from elements without resorting to jQuery often arises. This quest requires a thorough understanding of JavaScript's capabilities.

The Modern Approach: ClassList to the Rescue

To achieve this objective in a manner compliant with current web standards, the classList property shines as the preferred method. Supported by the majority of major browsers, this attribute provides a direct means of manipulating classes.

Implementation in Action

To illustrate the usage of classList, consider the following code snippet:

ELEMENT.classList.remove("CLASS_NAME");

Here's an example to provide further clarity:

<div>
function remove() {
  const el = document.querySelector('#el');
  el.classList.remove("red");
}

remove.onclick = () => {
  remove();
};

Within this code, the remove() function utilizes classList.remove() to eliminate the "red" class from the element with the ID el. Upon clicking the button with the ID remove, this action is triggered, resulting in the removal of the corresponding CSS style.

The above is the detailed content of How Can I Remove CSS Classes from Elements Using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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