EN
JavaScript - convert NodeList to Array
0 points
In this article, we would like to show you how to convert NodeList to Array in JavaScript.
Quick solution:
xxxxxxxxxx
1
var array = Array.from(nodeList);
In this example, we use from()
method to convert nodeList
to Array
type.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="container">Text node<span></span><div></div></div>
5
<script>
6
7
var container = document.querySelector('#container');
8
var nodeList = container.childNodes;
9
10
var array = Array.from(nodeList); // converts nodeList to Array type
11
12
console.log(array instanceof Array); // true
13
14
</script>
15
</body>
16
</html>
In this solution, we use the spread syntax (...
) to convert nodeList
to Array
type.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="container">Text node<span></span><div></div></div>
5
<script>
6
7
var container = document.querySelector('#container');
8
var nodeList = container.childNodes;
9
10
var array = [nodeList]; // converts nodeList to Array type
11
12
console.log(array instanceof Array); // true
13
14
</script>
15
</body>
16
</html>