diff options
author | Joris | 2020-02-03 18:28:50 +0100 |
---|---|---|
committer | Joris | 2020-02-03 18:28:50 +0100 |
commit | cbcc269be607cc964fbd69d179d8a0e8b8e4bffa (patch) | |
tree | 7a8135f7ede7e1ff02bc1cf1d697a8c39a56e962 /src/dom.ts | |
parent | c7e20a6dd01a2ae049c451d18511708aaee60a19 (diff) |
Extract dom and number utilities to external files
Diffstat (limited to 'src/dom.ts')
-rw-r--r-- | src/dom.ts | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/src/dom.ts b/src/dom.ts new file mode 100644 index 0000000..6b1c803 --- /dev/null +++ b/src/dom.ts @@ -0,0 +1,54 @@ +type Attribute = string | boolean | ((e: Event) => void) + +type Child = Element | string + +export function h(tag: string, attrs: {[key: string]: Attribute}, children: Array<Child> = []): Element { + let element = document.createElement(tag) + + for (let name in attrs) { + let value = attrs[name] + if (typeof value === 'boolean') { + if (value) { + element.setAttribute(name, name) + } + } else if (typeof value === 'function') { + (element as any)[name] = (e: Event) => { + (value as ((e: Event) => void))(e) + } + } else { + element.setAttribute(name, value) + } + } + + children.forEach(child => { + if (typeof child === 'string') { + element.appendChild(document.createTextNode(child)) + } else { + element.appendChild(child) + } + }) + + return element +} + +export function toggleClassName(node: Element, className: string) { + if (node.className === className) { + node.className = '' + } else { + node.className = className + } +} + +export function nodeListToArray(nodeList: NodeListOf<HTMLElement>): HTMLElement[] { + const xs: HTMLElement[] = []; + nodeList.forEach(node => xs.push(node)) + return xs +} + +export function replace(node: Node, replacement: Node) { + const parentNode = node.parentNode + + if (parentNode) { + parentNode.replaceChild(replacement, node) + } +} |