Skip to content

Instantly share code, notes, and snippets.

@nojvek nojvek/createElem.js
Created Mar 14, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.