-
Notifications
You must be signed in to change notification settings - Fork 0
/
htmlnodecollection.js
71 lines (53 loc) · 1.44 KB
/
htmlnodecollection.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
60
61
62
63
64
65
66
67
68
69
70
71
const HTMLNodeCollection = function(nodes) {
const _isValidNodes = function(nodes) {
return (nodes instanceof NodeList) || (nodes instanceof HTMLCollection);
};
if (!_isValidNodes(nodes)) {
throw new Error('nodes argument must be a NodeList, HTMLCollection or Array instance');
}
const _nodes = nodes;
const _cache = Array.from(_nodes);
this.length = _cache.length;
this[Symbol.iterator] = function() {
return _cache[Symbol.iterator]();
};
this.every = function(fn) {
return _cache.every(fn);
};
this.first = function() {
return _cache[0] || null;
};
this.forEach = function(fn) {
_cache.forEach(fn);
};
this.get = function(id) {
for (const node of _cache) {
if (node.id === id) {
return node;
}
}
return null;
};
this.isEmpty = function() {
return _cache.length === 0;
};
this.last = function() {
return _cache[_cache.length - 1] || null;
};
this.map = function(fn) {
return _cache.map(fn);
};
this.querySelector = function(selector) {
return _cache.find(node => node.matches(selector)) || null;
};
this.querySelectorAll = function(selector) {
return new HTMLNodeCollection(_cache.filter(node => node.matches(selector)));
};
this.some = function(fn) {
return _cache.some(fn);
};
};
const collectHTML = function(selector) {
const nodes = document.querySelectorAll(selector);
return new HTMLNodeCollection(nodes);
};