Created
December 14, 2025 16:45
-
-
Save vmsp/e2b10ba528c4aa557a5a6ab8912733b2 to your computer and use it in GitHub Desktop.
μCreateElement
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
| /** | |
| * @license | |
| * Copyright (c) 2025 Vitor Manuel de Sousa Pereira. All rights reserved. | |
| * SPDX-License-Identifier: MIT | |
| */ | |
| /** | |
| * @template {keyof HTMLElementTagNameMap | (string & {})} T | |
| * @typedef {(T extends keyof HTMLElementTagNameMap ? | |
| * Partial<HTMLElementTagNameMap[T]> : | |
| * Partial<HTMLElement>) | |
| * } ElementProps | |
| */ | |
| /** | |
| * Create a DOM element. | |
| * | |
| * @template {keyof HTMLElementTagNameMap | (string & {})} T | |
| * @param {T} type | |
| * @param {ElementProps<T> | Array<HTMLElement | string>} props | |
| * @param {Array<HTMLElement | string>} children | |
| */ | |
| export function createElement( | |
| type = /** @type {T} */ ("div"), | |
| props = /** @type {ElementProps<T>} */ ({}), | |
| children = [] | |
| ) { | |
| if (props?.constructor !== Object) { | |
| children = /** @type {Array<HTMLElement | string>} */ (props); | |
| props = /** @type {ElementProps<T>} */ ({}); | |
| } | |
| props = /** @type {ElementProps<T>} */ (props); | |
| if (!Array.isArray(children)) children = [children]; | |
| const el = document.createElement(type); | |
| Object.assign(el, props); | |
| Object.assign(el.style, props.style || {}); | |
| el.append(...children.filter(Boolean)); | |
| return el; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment