github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/client/src/dom.ts (about) 1 // Content managed by Project Forge, see [projectforge.md] for details. 2 export function els<T extends HTMLElement>(selector: string, context?: Element): readonly T[] { 3 let result: NodeListOf<Element>; 4 if (context) { 5 result = context.querySelectorAll(selector); 6 } else { 7 result = document.querySelectorAll(selector); 8 } 9 const ret: T[] = []; 10 result.forEach((v) => { 11 ret.push(v as T); 12 }); 13 return ret; 14 } 15 16 export function opt<T extends HTMLElement>(selector: string, context?: Element): T | undefined { 17 const e = els<T>(selector, context); 18 switch (e.length) { 19 case 0: 20 return undefined; 21 case 1: 22 return e[0]; 23 default: 24 console.warn(`found [${e.length}] elements with selector [${selector}], wanted zero or one`); 25 } 26 } 27 28 export function req<T extends HTMLElement>(selector: string, context?: Element): T { 29 const res = opt<T>(selector, context); 30 if (!res) { 31 throw new Error(`no element found for selector [${selector}]`); 32 } 33 return res; 34 } 35 36 export function setHTML(el: string | HTMLElement, html: string) { 37 if (typeof el === "string") { 38 el = req(el); 39 } 40 el.innerHTML = html; 41 return el; 42 } 43 44 export function setDisplay(el: string | HTMLElement, condition: boolean, v = "block") { 45 if (typeof el === "string") { 46 el = req(el); 47 } 48 49 el.style.display = condition ? v : "none"; 50 return el; 51 } 52 53 export function clear(el: string | HTMLElement) { 54 return setHTML(el, ""); 55 } 56 57 export function setText(el: string | HTMLElement, text: string): HTMLElement { 58 if (typeof el === "string") { 59 el = req(el); 60 } 61 el.innerText = text; 62 return el; 63 }