How to Add a Class Name to a HTML Element Using JavaScript?

Estimated read time 2 min read

To add a class name to an HTML element using JavaScript, you can use the className property of the element and assign a new string of class names to it.

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

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

// Add a class to the div element
myDiv.className += " newClass";

In this example, we first use the getElementById() method to get the div element with the ID of “myDiv”, and assign it to the myDiv variable. We then use the += operator to append the string ” newClass” to the existing className property of the myDiv element.

Note that when you use the className property to add a class name, you need to include a space before the new class name to separate it from any existing class names. If the className property is initially empty, you don’t need to include a space before the new class name.

You can add multiple class names to an element by separating each class name with a space. For example, you could add two classes to an element using the following code:

myDiv.className += " newClass1 newClass2";

Once you have added a class name 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