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
Release: 2024-12-10 19:59:09
Original
882 people have browsed it

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");
Copy after login

Similarly, to remove a class:

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

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>
Copy after login

Then, employ JavaScript:

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

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!

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