DEV Community

Cover image for A createElement one-liner (with attributes and children)
Rémy F.
Rémy F.

Posted on • Edited on

4 2

A createElement one-liner (with attributes and children)

The one-liner

el = (tag, props={}, ch=[]) => ch.reduce((e,c) => (e.appendChild(c),e),Object.assign(document.createElement(tag),props))
Enter fullscreen mode Exit fullscreen mode

Usage

el('ul',{classList:['list']},[
  el('li',{innerText:'first'}),
  el('li',{innerText:'second'}),
])
Enter fullscreen mode Exit fullscreen mode

Bonus: attributes support

el = (tag, props = {}, ch = [], attrs = {}) => ch.reduce((e, c) => (e.appendChild(c), e), Object.entries(attrs).reduce((e, [k, v]) => (e.setAttribute(k, v), e), Object.assign(document.createElement(tag), props)));
Enter fullscreen mode Exit fullscreen mode

Attributes Usage

el('ul',{classList:['list']},[
  el('li',{innerText:'first'}),
  el('li',{innerText:'second'}),
], {'data-example':42}) // ul extra attributes
Enter fullscreen mode Exit fullscreen mode

but_why.gif

In some cases, using only properties won't suffice:

el('input', {value: 42}) // input[value=42] won't match
el('input', {ariaLabel: "x"}) // input[aria-label] won't match (on FF)
el('input', {dataset: {a: 0}}) // dataset only has getter
Enter fullscreen mode Exit fullscreen mode

So now, you can set them by attributes:

el('input', {}, [], {value: 42}) // .value === '42'
el('input', {}, [], {'aria-label': "x"})
el('input', {}, [], {'data-a': 42}) // .dataset.a === '42'
Enter fullscreen mode Exit fullscreen mode

have a nice day

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay