Last active
June 2, 2025 03:29
-
-
Save daleblackwood/46f07c7481bb3aaef6ebaf7c12fbbdf0 to your computer and use it in GitHub Desktop.
One function dom lib with type completion.
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
/** | |
* @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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An example: