Home >Web Front-end >JS Tutorial >How do I remove CSS classes from elements using JavaScript?

How do I remove CSS classes from elements using JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 03:33:01608browse

How do I remove CSS classes from elements using JavaScript?

Removing CSS Classes with JavaScript

JavaScript offers a direct method for removing CSS classes from elements without the need for jQuery. This method employs the classList property, which is supported by most modern browsers.

Steps to Remove a CSS Class Using classList:

  1. Select the Element: Identify the element from which you want to remove the CSS class using document.querySelector or document.getElementById.
  2. Remove the Class: Utilize the classList.remove() method to remove the desired CSS class. The syntax is as follows:

    ELEMENT.classList.remove("CLASS_NAME");

Example:

To remove the "red" class from an element with the ID 'el', you would use the following code:

const el = document.querySelector('#el');
el.classList.remove("red");

Alternative Methods:

While classList.remove() is the recommended approach, there are alternative methods for removing CSS classes:

  • .removeAttribute(): This method removes an entire attribute, including the class name. However, it's less efficient than classList.remove().
  • Replacing the Class Attribute: You can replace the entire class attribute with a new value that excludes the class you want to remove.

The above is the detailed content of How do I remove CSS classes from elements using 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