diff options
author | metamuffin <metamuffin@disroot.org> | 2023-08-01 17:25:45 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2023-08-01 17:25:45 +0200 |
commit | 7b1cb4e58347758cab25b73dc6486f5f90efa6df (patch) | |
tree | aec1c130bdbf576394aeb3b488d8888f31eaa2f2 /frontend/helper.ts | |
parent | 7c933642730dd5b935281f2cc938f2998e3a4114 (diff) | |
download | fastbangs-7b1cb4e58347758cab25b73dc6486f5f90efa6df.tar fastbangs-7b1cb4e58347758cab25b73dc6486f5f90efa6df.tar.bz2 fastbangs-7b1cb4e58347758cab25b73dc6486f5f90efa6df.tar.zst |
refactor dom interaction with helper function
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 +} + |