Skip to content

Instantly share code, notes, and snippets.

@park-brian
Last active May 11, 2017 03:41
Show Gist options
  • Save park-brian/4965d09d069c2724c1eb5c0f024dac4a to your computer and use it in GitHub Desktop.
Save park-brian/4965d09d069c2724c1eb5c0f024dac4a to your computer and use it in GitHub Desktop.
createElement.js
/* Example usage:
* let el = createElement('div', {style: 'color: green'}, 'Hello world!');
* document.body.appendChild(el);
* /
export const createElement = (type, props, ...children) => {
if (type.constructor === Function)
return type(props);
let el = document.createElement(type);
for (let propName in props || {}) {
if (/^on/.test(propName))
el.addEventListener(
propName.substring(2).toLowerCase(),
props[propName]);
else
el[propName] = props[propName];
}
for (let child of children || []) {
if (child.constructor === String)
child = document.createTextNode(child);
el.appendChild(child);
}
return el;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment