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

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

Susan Sarandon
Release: 2024-12-22 14:00:24
Original
703 people have browsed it

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

Adding a Class to an Element in JavaScript

Introduction:
Enhancing the functionality of an element on a webpage often involves manipulating its CSS classes. Adding a new class can provide additional styles or behaviors to the element. This answer explains how to add a class to an element using JavaScript, considering support for modern browsers and legacy browsers.

Modern Browsers (Element.classList)
For modern browsers, including Chrome, Firefox, and Safari, the element.classList.add() method provides an efficient way to add a class to an element:

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

To remove the class later on:

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

Legacy Browsers (className Property)
For browsers like Internet Explorer 9 and lower, the className property of the element can be used to add a new class:

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

Ensure there's a space before the new class name to avoid compromising existing classes in the list.

Note: The element.className property can be used in modern browsers as well, but classList is generally a cleaner and more efficient approach.

The above is the detailed content of How to 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