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

How to Remove CSS Classes with JavaScript Without jQuery?

Mary-Kate Olsen
Release: 2024-11-11 17:33:03
Original
702 people have browsed it

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

Example

Consider the following HTML and CSS:

<div>
Copy after login
.red {
  background: red;
}
Copy after login

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template