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.

2

2 Answers

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);
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest