Home > Web Front-end > JS Tutorial > How Can I Add or Remove Classes from HTML Elements Using JavaScript?

How Can I Add or Remove Classes from HTML Elements Using JavaScript?

Mary-Kate Olsen
Release: 2024-12-15 22:58:10
Original
208 people have browsed it

How Can I Add or Remove Classes from HTML Elements Using JavaScript?

Adding a Class to an Element with JavaScript

When working with HTML elements, it often becomes necessary to add or remove classes dynamically using JavaScript. For instance, suppose you have an element with the following HTML:

<div class="someclass">
    <img ...>
Copy after login

And you want to create a JavaScript function that will add another class to the above div element.

Modern Browsers

If you're only targeting modern browsers that support the Element.classList property, the solution is straightforward. Simply use the classList.add() method to add a new class to the element:

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

To remove a class, use the classList.remove() method:

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

Internet Explorer 9 and Below

For older browsers like Internet Explorer 9 or lower, which do not support the classList property, you can use the className property. First, assign an ID to the element, making it easy to retrieve:

<div>
Copy after login

Then, concatenate the new class name with the existing one, ensuring a space is added between them:

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

Remember to include the space before the new class name to avoid conflicts with existing classes in the class list.

By following these approaches, you can dynamically add or remove classes from any HTML element using JavaScript, providing flexibility and control over the styling of your web pages.

The above is the detailed content of How Can I Add or Remove Classes from HTML Elements Using JavaScript?. 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