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");
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";
Ensure to include a space before the new class name, as this prevents conflicts with existing classes.
Additional Notes
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!