Can a new HTML element with a specific class name be created with JavaScript?

Viewed 43

I am trying to create an HTML element with a specific class name so when the content is on the DOM the CSS styles can be applied to it. It this possible ?

2 Answers

Just create the element and insert class inside it.

Ex:

// inside createElement function you have to type the tag name
const element = document.createElement('div')
element.classList.add('class-name')
// then you need to insert the element inside any element you want ( for example body element )
document.body.appendChild(element)

as @Mina said , you can use the element.classList.add("myClass").

Related