20

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');
user1941537
  • 4,891
  • 9
  • 43
  • 76
  • 2
    If your new `div` will be added to the DOM, you can also use HTML markup to describe it, and then `.insertAdjacentHTML` to create and add it. `var html = "
    "; targetElement.insertAdjacentHTML("beforeend", html);` That method gives you 4 positions relative to the target to which you can added to the DOM. See the docs for more info.
    – ziggy wiggy Mar 18 '19 at 15:26
  • 2
    This question still needs to be answered. It is not a duplicate of the proposed. This question is looking to add the classname in the same line. The duplicate is just looking to add a classname in general. – Whitecat Sep 17 '20 at 00:43

2 Answers2

46

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;
}
brk
  • 46,805
  • 5
  • 49
  • 71
3

You can use Element.classList.add

let div = document.createElement('div');
div.classList.add("myDiv")
R3tep
  • 11,845
  • 10
  • 43
  • 71