function el(tag, props = {}, ...children) {
const node = document.createElement(tag);
for (const [key, val] of Object.entries(props)) {
if (key.startsWith('on') && typeof val === 'function') {
node.addEventListener(key.slice(2).toLowerCase(), val);
} else if (key === 'style' && typeof val === 'object') {
Object.assign(node.style, val);
} else {
node[key] = val;
}
}
node.append(...children.flat().map((c) =>
c instanceof Node ? c : document.createTextNode(String(c))
));
return node;
}
// Usage
const card = el('div', { className: 'card' },
el('h2', {}, 'Hello'),
el('button', { onClick: () => alert('hi!') }, 'Click me')
);
document.body.appendChild(card);
Create a free account and build your private vault. Share publicly whenever you want.