Objective:
Enhance an HTML element with an extra class qualification.
Scenario:
Given an element with an existing class, we aim to add a new class without overwriting the original one.
Solution:
Utilizing the classList property, you can effortlessly add a class to an element:
element.classList.add("my-class");
Similarly, to remove a class:
element.classList.remove("my-class");
To cater to older browsers like Internet Explorer 9, modify the element's className property by appending a space followed by the new class name. As a prerequisite, assign an id to the element for convenient access:
<div>
Then, employ JavaScript:
var d = document.getElementById("div1"); d.className += " otherclass";
Remember to include a leading space before "otherclass" to preserve existing class qualifiers.
Refer to the Mozilla Developer Network (MDN) for comprehensive documentation on element.className.
The above is the detailed content of How to Add a New Class to an HTML Element Without Overwriting Existing Classes?. For more information, please follow other related articles on the PHP Chinese website!