forked from yuanqing/charming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (48 loc) · 1.4 KB
/
index.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module.exports = function (
element,
{
tagName = 'span',
split,
setClassName = function (index) {
return 'char' + index
}
} = {}
) {
element.normalize()
let index = 1
function inject (element) {
const parentNode = element.parentNode
const nodeValue = element.nodeValue
const array = split ? split(nodeValue) : nodeValue.split('')
array.forEach(function (string) {
const node = document.createElement(tagName)
const className = setClassName(index++, string)
if (className) {
node.className = className
}
node.appendChild(document.createTextNode(string))
node.setAttribute('aria-hidden', 'true')
parentNode.insertBefore(node, element)
})
if (nodeValue.trim() !== '') {
parentNode.setAttribute('aria-label', nodeValue)
}
parentNode.removeChild(element)
}
;(function traverse (element) {
// `element` is itself a text node
if (element.nodeType === 3) {
return inject(element)
}
// `element` has a single child text node
const childNodes = Array.prototype.slice.call(element.childNodes) // static array of nodes
const length = childNodes.length
if (length === 1 && childNodes[0].nodeType === 3) {
return inject(childNodes[0])
}
// `element` has more than one child node
childNodes.forEach(function (childNode) {
traverse(childNode)
})
})(element)
}