um/src/tag.js

27 lines
732 B
JavaScript
Raw Normal View History

2024-05-05 00:34:27 +00:00
/**
* Creates new DOM element(s) from tag name(s) and attributes
*
* @param {string} tag - tag to create
* @param {...any} args - attributes and/or child tag elements
*
* @returns {HTMLElement} The created DOM element(s)
*/
export default function tag(tag, ...args) {
const el = document.createElement(tag);
2024-05-05 19:00:47 +00:00
// support all scalar values as TextNodes
const isScalar = (value) => ["boolean", "string", "number"].includes(typeof value);
2024-05-05 00:34:27 +00:00
args.forEach((arg) => {
2024-05-05 19:00:47 +00:00
if (isScalar(arg)) {
2024-05-05 00:34:27 +00:00
el.appendChild(document.createTextNode(arg));
} else if (Array.isArray(arg)) {
el.append(...arg);
} else {
Object.assign(el, arg);
}
});
return el;
}