Here are two ways that I know to create an element and assign it a class:
const el = document.createElement('div');
el.classList.add('foo');
const el = document.createElement('div');
foo.className = 'foo';
Is there a one-step solution for it? I tried
const el = document.createElement('div').classList.add('foo');
but it doesn't work.
Here are two ways that I know to create an element and assign it a class:
const el = document.createElement('div');
el.classList.add('foo');
const el = document.createElement('div');
foo.className = 'foo';
Is there a one-step solution for it? I tried
const el = document.createElement('div').classList.add('foo');
but it doesn't work.
let el = '<div class="foo">Content here</div>';
and insert using innerHTML
or insertAdjacentHTML()
– Randy Casburn
Commented
Feb 19, 2021 at 21:47
Although the usual way to do it is a two-step technique, try this:
const el = Object.assign(document.createElement('div'), { className: 'foo' });
console.log(el);
console.log(el.className);
You're stuck with either using an HTML string and innerHTML or trying jQuery which allows the chaining of mands, but for something so small it doesn't make sense to bring jQuery into the mix, what's the reason you needed a one-liner?
For a rough working example in vanilla js
var myHTML = "<div class='hello'></div>";
document.body.innerHTML += myHTML