How to Add a Tag with a Class in HTML Using JavaScript?

Estimated read time 1 min read

To add an HTML tag with a class using JavaScript, you can create a new element using the document.createElement() method, set its class using the classList property, and append it to the desired parent element using the appendChild() method.

Here’s an example that shows how to add a div tag with a class of “my-class” to the body of the HTML document using JavaScript:

// Create a new div element
var newDiv = document.createElement("div");

// Add the "my-class" class to the div element
newDiv.classList.add("my-class");

// Append the new div element to the body of the HTML document
document.body.appendChild(newDiv);

In this example, we create a new div element using the document.createElement() method and assign it to the newDiv variable. We then use the classList property of the newDiv element to add the class of “my-class” to it.

Finally, we use the appendChild() method of the document.body element to add the newDiv element to the body of the HTML document.

You can replace “div” with any other HTML tag you need to add, and “my-class” with the class name you want to use.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply