Abdulhameed Mustapha
Abdulhameed Mustapha

Reputation: 119

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

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 ?

Upvotes: 1

Views: 957

Answers (2)

hasan darwish
hasan darwish

Reputation: 174

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

Upvotes: 2

Mina
Mina

Reputation: 17039

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)

Upvotes: 3

Related Questions