Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Created October 5, 2017 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/b558005402b41fe2e33fe9439c3fc571 to your computer and use it in GitHub Desktop.
Save JosePedroDias/b558005402b41fe2e33fe9439c3fc571 to your computer and use it in GitHub Desktop.
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;
}
@JosePedroDias
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment