How to Add a Class to an HTML Tag Using JavaScript?

Estimated read time 1 min read

To add a class to an HTML tag using JavaScript, you can use the classList property of the element and call its add() method to add the class name.

Here’s an example of how to add a class to an h1 element using JavaScript:

// Get the h1 element by its ID
var myHeading = document.getElementById("myHeading");

// Add a class to the h1 element
myHeading.classList.add("myClass");

In this example, we first use the getElementById() method to get the h1 element with the ID of “myHeading”, and assign it to the myHeading variable. We then use the classList.add() method to add a class name of “myClass” to the myHeading element.

You can add multiple classes to an element by calling the classList.add() method multiple times, passing in each class name as a separate argument. You can also use the classList.remove() method to remove a class from an element, or the classList.toggle() method to toggle a class on or off.

Once you have added a class to an element, you can use CSS to style the element based on its class name.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply