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');
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 = "<div class=myDiv></div>"; 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.