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");
To remove the class later on:
element.classList.remove("my-class");
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";
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!