EN
JavaScript - create new NodeList() from node array
8 points
In this short article we would like to show how to create custom NodeList class in JavaScript.
By default NodeList
class doesn't provide public constructor, so custom one lets to use new
operator to create the object.
Quick solution:
xxxxxxxxxx
1
const createNodeList = (array) => {
2
const fragment = new DocumentFragment();
3
for (const item of array) {
4
fragment.appendChild(item);
5
}
6
return fragment.childNodes;
7
};
8
9
10
// Usage example:
11
12
const list = createNodeList([/* ... */]);
In this section you can find DOM-based solution.
xxxxxxxxxx
1
const createNodeList = (array) => {
2
const fragment = new DocumentFragment();
3
for (const item of array) {
4
fragment.appendChild(item);
5
}
6
return fragment.childNodes;
7
};
8
9
10
11
// Usage example:
12
13
const nodes = [
14
document.createElement('div'),
15
document.createElement('div'),
16
document.createElement('div')
17
];
18
19
const list = createNodeList(nodes);
20
21
for (const node of list) {
22
console.log(node);
23
}
This solution doesn't need DOM support, so it may be run under Node.js.
Hint: working under Node.js we should remove line with NodeList.prototype from the below source code and use other way to create elements than document object, e.g. some library or own custom logic.
xxxxxxxxxx
1
function CustomNodeList(nodes) {
2
const iterator = nodes[Symbol.iterator];
3
Object.defineProperty(this, 'length', {
4
get: function() {
5
return nodes.length;
6
}
7
});
8
this.item = function(index) {
9
if (index === undefined) {
10
throw new TypeError(`Failed to execute 'item' on 'NodeList': 1 argument required, but only 0 present.`);
11
}
12
return nodes[index] ?? null;
13
};
14
this.keys = function() {
15
return nodes.keys();
16
};
17
this.values = function() {
18
return nodes.values();
19
};
20
this.entries = function() {
21
return nodes.entries();
22
};
23
this.forEach = function(callback) {
24
nodes.forEach(callback);
25
};
26
this[Symbol.iterator] = function() {
27
return iterator.call(nodes);
28
};
29
return new Proxy(this, {
30
get: function(target, name) {
31
return (name in target ? target[name] : nodes[name]);
32
}
33
});
34
};
35
36
CustomNodeList.prototype = NodeList.prototype;
37
38
39
40
// Usage example:
41
42
const nodes = [
43
document.createElement('div'),
44
document.createElement('div'),
45
document.createElement('div')
46
];
47
48
const list = new CustomNodeList(nodes);
49
50
for (const node of list) {
51
console.log(node);
52
}