Reputation: 975
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.
Upvotes: 4
Views: 7349
Reputation: 28414
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);
Upvotes: 10
Reputation: 1608
You're stuck with either using an HTML string and innerHTML or trying jQuery which allows the chaining of commands, 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
Upvotes: 2