[Solved] document.createElement(‘div’) with a class [duplicate]

I can use createElement() to create an HTML element via JavaScript like this:

let div = document.createElement('div');

But how can I add a CSS class to my newly created div?

I tried something like this, but didn’t work:

let div = document.createElement('div class=myDiv');

Solution #1:

Do div.classList.add

let div = document.createElement('div');
div.classList.add('test');
let text = document.createTextNode('Test');
div.appendChild(text);
document.body.appendChild(div)
.test {
  color: green;
}

You can also do by className

let div = document.createElement('div');
div.className = 'test';
let text = document.createTextNode('Test');
div.appendChild(text);
document.body.appendChild(div)
.test {
  color: red;
}

Respondent: brk

Solution #2:

You can use Element.classList.add

let div = document.createElement('div');
div.classList.add("myDiv")
Respondent: R3tep

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.