The one-liner
el = (tag, props={}, ch=[]) => ch.reduce((e,c) => (e.appendChild(c),e),Object.assign(document.createElement(tag),props))
Usage
el('ul',{classList:['list']},[
el('li',{innerText:'first'}),
el('li',{innerText:'second'}),
])
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)));
Attributes Usage
el('ul',{classList:['list']},[
el('li',{innerText:'first'}),
el('li',{innerText:'second'}),
], {'data-example':42}) // ul extra attributes
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
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'
have a nice day
Top comments (0)