Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created June 12, 2025 00:43
Show Gist options
  • Select an option

  • Save NickStrupat/95d80da4565de8d4f343f0835d3d25e5 to your computer and use it in GitHub Desktop.

Select an option

Save NickStrupat/95d80da4565de8d4f343f0835d3d25e5 to your computer and use it in GitHub Desktop.

Revisions

  1. NickStrupat created this gist Jun 12, 2025.
    21 changes: 21 additions & 0 deletions el.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    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();
    }
    }