Home >Web Front-end >JS Tutorial >How to Add a New Class to an HTML Element Without Overwriting Existing Classes?

How to Add a New Class to an HTML Element Without Overwriting Existing Classes?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 19:59:09910browse

How to Add a New Class to an HTML Element Without Overwriting Existing Classes?

How to Add an Additional Class to an Existing Element

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:

For Modern Browsers

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");

For Legacy Support

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.

Additional Considerations

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!

Statement:
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