26

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
  • 6,097
  • 14
  • 52
  • 99
  • 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

61

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
  • 48,835
  • 10
  • 56
  • 78
7

You can use Element.classList.add

let div = document.createElement('div');
div.classList.add("myDiv")
R3tep
  • 12,512
  • 10
  • 48
  • 75