26 lines
900 B
TypeScript
26 lines
900 B
TypeScript
// Kleine DOM-Helfer ohne Framework.
|
|
|
|
type Child = Node | string | null | undefined | false
|
|
|
|
/** Element mit Klassen und Kindern: h('div.card.big', 'Text', h('b', '1')) */
|
|
export function h<K extends keyof HTMLElementTagNameMap>(
|
|
tagAndClasses: K | `${K}.${string}`,
|
|
...children: Child[]
|
|
): HTMLElementTagNameMap[K] {
|
|
const [tag, ...classes] = tagAndClasses.split('.') as [K, ...string[]]
|
|
const el = document.createElement(tag)
|
|
if (classes.length) el.className = classes.join(' ')
|
|
for (const c of children) if (c) el.append(c)
|
|
return el
|
|
}
|
|
|
|
export function byId<T extends HTMLElement>(id: string): T {
|
|
const el = document.getElementById(id)
|
|
if (!el) throw new Error(`#${id} fehlt`)
|
|
return el as T
|
|
}
|
|
|
|
/** Kinder ohne Lücken (für replaceChildren) */
|
|
export function nodes(...children: Child[]): (Node | string)[] {
|
|
return children.filter((c): c is Node | string => Boolean(c))
|
|
}
|