Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created June 12, 2025 00:43
Show Gist options
  • Save NickStrupat/95d80da4565de8d4f343f0835d3d25e5 to your computer and use it in GitHub Desktop.
Save NickStrupat/95d80da4565de8d4f343f0835d3d25e5 to your computer and use it in GitHub Desktop.
A function for creating DOM elements with attributes and nested children.
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