Created
June 12, 2025 00:43
-
-
Save NickStrupat/95d80da4565de8d4f343f0835d3d25e5 to your computer and use it in GitHub Desktop.
A function for creating DOM elements with attributes and nested children.
This file contains hidden or 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
export function el<T extends keyof HTMLElementTagNameMap>( | |
tag: T, | |
attrs: Partial<HTMLElementTagNameMap[T] & { class: string | string[] } & { [K: `data-${string}`]: any; }> = {}, | |
...children: (HTMLElement | string)[] | |
): HTMLElementTagNameMap[T] { | |
const element = document.createElement(tag); | |
for (const [key, value] of Object.entries(attrs)) | |
element.setAttribute(key, getAttrValue(key, value)); | |
for (const child of children) | |
element.appendChild(typeof child === 'string' ? document.createTextNode(child) : child); | |
return element; | |
function getAttrValue(key: string, value: any): string { | |
if (key === 'class') | |
return Array.isArray(value) ? value.join(' ') : value.toString(); | |
else if (key.startsWith('on') && typeof value === 'function') | |
return `(${value.toString()})()`; | |
else | |
return value.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment