diff options
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) + } +} |