Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
create elements in a snabbdom-like way, without any virtual thingie. small and opinionated.
function EL(_nodeName, _attrs, _children) {
let attrs = {}, children = [];
const argLen = arguments.length;
if (argLen === 1) { return document.createTextNode(_nodeName); }
else if (argLen === 2) {
if (_attrs instanceof Array) { children = _attrs; }
else if (_attrs instanceof Object) { attrs = _attrs; }
else { throw new Error('2nd arg must be either an object (attrs) or an array (children)!'); }
}
else if (argLen === 3) { attrs = _attrs; children = _children; }
else { throw new Error('Wrong number of params!'); }
const classes = (_nodeName.indexOf('.') === -1) ? [_nodeName] : _nodeName.split('.');
const nodeName = classes.shift();
const el = document.createElement(nodeName);
classes.forEach(cl => el.classList.add(cl));
Object.keys(attrs).forEach(at => {
if (at.substring(0, 2) === 'on') {
el.addEventListener(at.substring(2), attrs[at]);
} else {
el.setAttribute(at, attrs[at]);
}
});
children.forEach(chEl => el.appendChild(typeof chEl === 'string' ? EL(chEl) : chEl));
return el;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment