Create element and assign class in one step

Here are two ways that are known to me to create an element and assign it a class:

const el = document.createElement('div');
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.

127 thoughts on “Create element and assign class in one step”

Leave a Comment