Home  >  Article  >  Web Front-end  >  How to Remove CSS Classes with JavaScript Without jQuery?

How to Remove CSS Classes with JavaScript Without jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 17:33:03618browse

How to Remove CSS Classes with JavaScript Without jQuery?

Removing CSS Classes with JavaScript Without jQuery

Removing a CSS class from an element using JavaScript is a common task in web development. To accomplish this without jQuery, there are several approaches, with the most straightforward being the use of the classList property.

Using classList

The classList property provides a simple interface for manipulating classes on an element. To remove a specific class, simply use the remove() method:

ELEMENT.classList.remove("CLASS_NAME");

Example

Consider the following HTML and CSS:

<div>
.red {
  background: red;
}

To remove the "red" class from the "el" element using classList, the following code can be used:

var el = document.getElementById("el");
el.classList.remove("red");

Alternative Approaches

While classList is the most recommended approach, there are alternative ways to remove classes, such as:

  • Attribute Manipulation: Setting the className attribute to the new class list without the target class.
  • Regular Expression Replacement: Using replace() to remove the target class from the className string.

However, these methods are less efficient and flexible compared to using classList.

The above is the detailed content of How to Remove CSS Classes with JavaScript Without jQuery?. 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