Skip to content

Instantly share code, notes, and snippets.

@nojvek
Created March 14, 2019 18:11
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 nojvek/9612df140a0bb3f38b441aabe501102b to your computer and use it in GitHub Desktop.
Save nojvek/9612df140a0bb3f38b441aabe501102b to your computer and use it in GitHub Desktop.
createEleme - simple dom helper for creating dom nodes
/**
* A simple helper for creating nested dom tree inspired by snabbdom-jsx syntax
* @param {string} name
* @param {{[attr: string]: any}} attrs
* @param {Array<HTMLElement | string>} children
* @returns {HTMLElement}
*/
export function createElem(name, attrs, children) {
const elem = document.createElement(name);
for (const [attr, val] of Object.entries(attrs || {})) {
const match = attr.match(/^(prop|class|on|)-([\w-]+)$/);
if (match) {
const [_, prefix, name] = match; // eslint-disable-line no-unused-vars
if (prefix === `prop`) {
elem[name] = val;
} else if (prefix === `class` && val) {
elem.classList.add(name);
} else if (prefix === `on`) {
elem.addEventListener(name, val);
}
} else {
elem.setAttribute(attr, val);
}
}
if (!Array.isArray(children)) {
children = [children];
}
for (const child of children) {
if (typeof child === `string`) {
elem.appendChild(document.createTextNode(child));
} else if (child) {
elem.appendChild(child);
}
}
return elem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment