user90726
user90726

Reputation: 975

Create element and assign class in one step

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

Answers (2)

Majed Badawi
Majed Badawi

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

Da Mahdi03
Da Mahdi03

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

Related Questions