Skip to content

Instantly share code, notes, and snippets.

@daleblackwood
Last active June 2, 2025 03:29
Show Gist options
  • Save daleblackwood/46f07c7481bb3aaef6ebaf7c12fbbdf0 to your computer and use it in GitHub Desktop.
Save daleblackwood/46f07c7481bb3aaef6ebaf7c12fbbdf0 to your computer and use it in GitHub Desktop.
One function dom lib with type completion.
/**
* @template {keyof HTMLElementTagNameMap | HTMLElement} T
* @param {T} tagOrEl
* @param {(
* Omit<Partial<T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T>, "style", "parentNode", "parentElement"> &
* { style?: Partial<CSSStyleDeclaration> } &
* { [key: string]: unknown }
* ) | null | undefined} [props={}]
* @param {HTMLElement[]} [children]
* @returns {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T}
*/
export function dom(tagOrEl, props, children) {
/** @type {any} */ const el = tagOrEl instanceof HTMLElement ? tagOrEl : document.createElement(tagOrEl);
const { style, ...rest } = props || {};
style && typeof style === "object" && Object.assign(el.style, style);
for (const [k, v] of Object.entries(rest)) {
if (k in el && el[k] !== v)
el[k] = v;
else if (el.getAttribute(k) !== String(v))
el.setAttribute(k, String(v));
}
if (Array.isArray(children)) {
while (el.firstChild)
el.removeChild(el.firstChild);
children.forEach(c => c && el.appendChild(c));
}
return el;
}
export default dom;
@daleblackwood
Copy link
Author

An example:

dom(document.body, null, [
    dom("div", { style: { position: "absolute", inset: "0" } }, [
        dom("video", { id: "vid", src: "https://51b5cd51-0a30-4ae1-aeb0-10a9f6e3aefb.mdnplay.dev/shared-assets/videos/flower.webm", style: { width: "100%" } }),
        dom("button", { onclick: e => document.getElementById("vid").play(), style: { position: "absolute", bottom: 0, left: 0 }, innerText: "Play" })
    ])
]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment