Home > Web Front-end > JS Tutorial > How Do I Add a Class to an HTML Element Using JavaScript?

How Do I Add a Class to an HTML Element Using JavaScript?

Barbara Streisand
Release: 2024-12-16 02:47:13
Original
346 people have browsed it

How Do I Add a Class to an HTML Element Using JavaScript?

How to Add a Class to a Given Element Using JavaScript

To add a class to an existing element, you can utilize several approaches, depending on browser compatibility requirements.

Modern Browsers

For modern browsers, the classList property provides a straightforward solution:

element.classList.add("my-class");
Copy after login

This code will add the "my-class" class to the specified element. To remove a class, use classList.remove.

Internet Explorer 9 and Lower

For older browsers like Internet Explorer 9 and below, you can manually modify the className property:

var d = document.getElementById("div1");
d.className += " otherclass";
Copy after login

Ensure to include a space before the new class name, as this prevents conflicts with existing classes.

Additional Notes

  • The classList property is supported in all major modern browsers, including Chrome, Firefox, Safari, Edge, and Opera.
  • For more information on the classList property and other methods for manipulating classes, refer to the MDN documentation on element.className.

The above is the detailed content of How Do I Add a Class to an HTML Element Using JavaScript?. 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