Created
March 14, 2019 18:11
-
-
Save nojvek/9612df140a0bb3f38b441aabe501102b to your computer and use it in GitHub Desktop.
createEleme - simple dom helper for creating dom nodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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