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.

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

  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
  2. Although the right way to do it is a two-step technique, try this:

    const el = Object.assign(document.createElement('div'), {
        className: 'foo'

Leave a Comment