Skip to content

Instantly share code, notes, and snippets.

@vmsp
Created December 14, 2025 16:45
Show Gist options
  • Select an option

  • Save vmsp/e2b10ba528c4aa557a5a6ab8912733b2 to your computer and use it in GitHub Desktop.

Select an option

Save vmsp/e2b10ba528c4aa557a5a6ab8912733b2 to your computer and use it in GitHub Desktop.
μCreateElement
/**
* @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