-
Notifications
You must be signed in to change notification settings - Fork 47
/
classApi.js
38 lines (36 loc) · 1.01 KB
/
classApi.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
/**
* @desc classApi
|*| * classApi.isElement(el)
|*| * classApi.hasClass(el,cls)
|*| * classApi.addClass(el,cls)
|*| * classApi.removeClass(el,cls)
|*| * classApi.toggleClass(el,cls)
*/
var classApi = {
isElement: function isElement(el) {
return el && el.nodeType === Node.ELEMENT_NODE;
},
hasClass: function hasClass(el, cls) {
return new RegExp('(\\s|^)' + cls + '(\\s|$)').test(el.className);
},
addClass: function addClass(el, cls) {
if (!this.hasClass(el, cls)) {
el.className += ' ' + cls;
}
},
removeClass: function removeClass(el, cls) {
if (this.hasClass(el, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
el.className = el.className.replace(reg, ' ');
}
},
toggleClass: function toggleClass(el, cls) {
if (this.hasClass(el, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
el.className = el.className.replace(reg, ' ');
} else {
el.className += ' ' + cls;
}
}
};
module.exports = classApi;