Home > Web Front-end > JS Tutorial > How to Remove a CSS Class from an Element Using JavaScript (Without jQuery)?

How to Remove a CSS Class from an Element Using JavaScript (Without jQuery)?

Mary-Kate Olsen
Release: 2024-11-08 20:30:02
Original
957 people have browsed it

How to Remove a CSS Class from an Element Using JavaScript (Without jQuery)?

How to Remove CSS Class from Element Using JavaScript (Without jQuery)

Question: Can someone guide me on how to remove a class from an HTML element purely with JavaScript, excluding jQuery?

Answer:

The preferred approach is to utilize the classList property. It is widely supported across modern browsers.

To remove a class, simply use the following syntax:

ELEMENT.classList.remove("CLASS_NAME");
Copy after login

Example:

Consider a button element with a class named "red" to demonstrate this concept:

<button>
Copy after login

When the button is clicked, the following JavaScript code removes the "red" class from an element with the ID "el":

remove.onclick = () => {
  const el = document.querySelector('#el');
  el.classList.remove("red");
};
Copy after login

This action alters the CSS styles applied to the element with the "el" ID, effectively removing the reddish background:

.red {
  background: red
}
Copy after login

The above is the detailed content of How to Remove a CSS Class from an Element Using JavaScript (Without jQuery)?. For more information, please follow other related articles on the PHP Chinese website!

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