-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnswer.js
More file actions
129 lines (113 loc) · 3.3 KB
/
Answer.js
File metadata and controls
129 lines (113 loc) · 3.3 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
var $ = function (selector) {
selector = selector.replace(/\s+/g,' ').replace(/^\s+|\s+$/,'');
if(!selector){
throw Error('Expected selector');
}
if(typeof selector !== 'string'){
throw TypeError('Expected string');
}
//quick check
var match = /^(?:([#\.])?([\w-]+))$/.exec(selector);
if(match){
var type = match[1];
if(type === '#'){
var element = document.getElementById(match[2]);
return element ? [element] : [];
}else if(type === '.'){ // by CLASS
return byClass(match[2]);
}else{ //by TAG
return toArray(document.getElementsByTagName(match[2]));
}
}
//something more complicated
var filters = {
id:function(item, id){
return item.id === id;
},
class:function(item, klass){
if(item.classList){
return item.classList.contains(klass);
}
return item.className.split(' ').indexOf(klass) !== -1;
},
tag:function(item, tag){
return item.tagName.toLowerCase() === tag;
}
};
var finders = {
id:function(value){
var element = document.getElementById(value);
return element ? [element] : [];
},
tag:function(value){
return toArray(document.getElementsByTagName(value));
},
class:function(value){
return byClass(value);
}
};
var query = {
id:'',
tag:'',
class:''
};
parse(query, selector);
var elements = [];
for(var name in finders){
if(query[name]){
var finder = finders[name];
elements = finder(query[name]);
delete query[name]; // future filters without finding rule
break;
}
}
elements = elements.filter(filterItem);
function filterItem(item){
for(var name in filters){
if(query[name]){
var filter = filters[name];
if(!filter(item, query[name])){
return false;
}
}
}
return true;
}
function parse(query, selector){
var pattern = /^([#\.])?([\w-]+)/;
search();
search();
search();
function search(){
if(selector){
match = pattern.exec(selector);
if(match){
var value = match[2];
var sign = match[1];
query[type(sign)] = value;
selector = selector.slice(value.length + (sign ? 1 : 0));
}
}
}
function type(sign){
switch (sign) {
case '#': return 'id';
case '.': return 'class';
default: return 'tag';
}
}
}
function toArray(items){
return Array.prototype.slice.call(items);
}
function byClass(selector){
if(document.getElementsByClassName){
return document.getElementsByClassName(selector);
}
var elements = toArray(document.getElementsByTagName('*'));
return elements.filter(function(item){
return filters.class(item, selector);
});
}
return elements;
};