DEV Community

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

Posted on • Edited on

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)