forked from choojs/nanohtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
appendChild.js
34 lines (29 loc) · 1.02 KB
/
appendChild.js
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
31
32
33
34
const parseNodeAsString = node => (typeof node === 'number' ||
typeof node === 'boolean' ||
typeof node === 'function' ||
node instanceof Date ||
node instanceof RegExp) ? node.toString() : node
const isNotWhitespace = node => !(typeof node === 'string' && /^[\n\r\s]+$/.test(node))
const appendChild = (element, childs) => {
if (!Array.isArray(childs)) return
childs
.map(parseNodeAsString)
.filter(isNotWhitespace)
.forEach((node) => {
if (Array.isArray(node)) {
appendChild(element, node)
return
}
if (typeof node === 'string') {
if (element.lastChild && element.lastChild.nodeName === '#text') {
element.lastChild.nodeValue += node
return
}
node = document.createTextNode(node)
}
if (node && node.nodeType) {
element.appendChild(node)
}
})
}
module.exports = appendChild