diff options
Diffstat (limited to 'frontend/helper.ts')
-rw-r--r-- | frontend/helper.ts | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/frontend/helper.ts b/frontend/helper.ts new file mode 100644 index 0000000..f47d131 --- /dev/null +++ b/frontend/helper.ts @@ -0,0 +1,30 @@ + + +interface Opts<E> { + class?: string[] | string, + id?: string, + src?: string, + for?: string, + onclick?: (e: E) => void, + onchange?: (e: E) => void, +} + +function apply_opts<E extends HTMLElement>(e: E, o: Opts<E>) { + if (o.id) e.id = o.id + if (o.onclick) e.onclick = () => o.onclick!(e) + if (o.onchange) e.onchange = () => o.onchange!(e) + if (o.for) (e as unknown as HTMLLabelElement).htmlFor = o.for + if (typeof o?.class == "string") e.classList.add(o.class) + if (typeof o?.class == "object") e.classList.add(...o.class) +} + +export function e<K extends keyof HTMLElementTagNameMap>(name: K, opts: Opts<HTMLElementTagNameMap[K]>, ...children: (HTMLElement | string)[]): HTMLElementTagNameMap[K] { + const el = document.createElement(name) + apply_opts(el, opts) + for (const c of children) { + if (typeof c == "string") el.textContent += c; + else el.append(c) + } + return el +} + |