aboutsummaryrefslogtreecommitdiff
path: root/src/h.ts
blob: bb21efd37a2a2a06580ebcd64506197786526de3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
type Child = Element | Text | string | number

export default function h(
  tagName: string,
  attrs: object,
  ...children: Child[]
): Element {
  const isSvg = tagName === 'svg' || tagName === 'path'

  let elem = isSvg
    ? document.createElementNS('http://www.w3.org/2000/svg', tagName)
    : document.createElement(tagName)

  if (isSvg) {
    Object.entries(attrs).forEach(([key, value]) => {
      elem.setAttribute(key, value)
    })
  } else {
    elem = Object.assign(elem, attrs)
  }

  for (const child of children) {
    if (typeof child === 'number')
      elem.append(child.toString())
    else
      elem.append(child)
  }

  return elem
}