class-util.js
1.45 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* @flow */
const whitespaceRE = /\s+/
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
export function addClass (el: HTMLElement, cls: ?string) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(whitespaceRE).forEach(c => el.classList.add(c))
} else {
el.classList.add(cls)
}
} else {
const cur = ` ${el.getAttribute('class') || ''} `
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim())
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
export function removeClass (el: HTMLElement, cls: ?string) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(whitespaceRE).forEach(c => el.classList.remove(c))
} else {
el.classList.remove(cls)
}
if (!el.classList.length) {
el.removeAttribute('class')
}
} else {
let cur = ` ${el.getAttribute('class') || ''} `
const tar = ' ' + cls + ' '
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ')
}
cur = cur.trim()
if (cur) {
el.setAttribute('class', cur)
} else {
el.removeAttribute('class')
}
}
}