-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
59 lines (51 loc) · 1.55 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
49
50
51
52
53
54
55
56
57
58
59
module.exports = function(opts) {
return new ElementClass(opts)
}
function indexOf(arr, prop) {
if (arr.indexOf) return arr.indexOf(prop)
for (var i = 0, len = arr.length; i < len; i++)
if (arr[i] === prop) return i
return -1
}
function ElementClass(opts) {
if (!(this instanceof ElementClass)) return new ElementClass(opts)
var self = this
if (!opts) opts = {}
// similar doing instanceof HTMLElement but works in IE8
if (opts.nodeType) opts = {el: opts}
this.opts = opts
this.el = opts.el || document.body
if (typeof this.el !== 'object') this.el = document.querySelector(this.el)
}
ElementClass.prototype.add = function(className) {
var el = this.el
if (!el) return
if (el.className === "") return el.className = className
var classes = el.className.split(' ')
if (indexOf(classes, className) > -1) return classes
classes.push(className)
el.className = classes.join(' ')
return classes
}
ElementClass.prototype.remove = function(className) {
var el = this.el
if (!el) return
if (el.className === "") return
var classes = el.className.split(' ')
var idx = indexOf(classes, className)
if (idx > -1) classes.splice(idx, 1)
el.className = classes.join(' ')
return classes
}
ElementClass.prototype.has = function(className) {
var el = this.el
if (!el) return
var classes = el.className.split(' ')
return indexOf(classes, className) > -1
}
ElementClass.prototype.toggle = function(className) {
var el = this.el
if (!el) return
if (this.has(className)) this.remove(className)
else this.add(className)
}