Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement