Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert a node list to an array in JavaScript?
A NodeList is returned by DOM methods like querySelectorAll() and getElementsByClassName(). While it's array-like, it doesn't have all array methods. Converting it to a true array gives you access to methods like map(), filter(), and forEach().
Using Array.from() (Recommended)
The Array.from() method is the modern and most readable way to convert a NodeList to an array:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Convert NodeList to Array</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 20px;
}
.sample {
display: inline-block;
font-size: 20px;
font-weight: 500;
color: white;
background-color: blue;
padding: 10px;
width: 100px;
height: 100px;
margin: 5px;
text-align: center;
line-height: 100px;
}
button {
margin: 10px 5px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Convert NodeList to Array Examples</h1>
<div class="sample">1</div>
<div class="sample">2</div>
<div class="sample">3</div>
<div class="sample">4</div>
<br>
<button onclick="useArrayFrom()">Array.from()</button>
<button onclick="useSpread()">Spread Operator</button>
<button onclick="resetColors()">Reset</button>
<div id="output"></div>
<script>
function useArrayFrom() {
// Get NodeList
let nodeList = document.querySelectorAll('.sample');
console.log('NodeList type:', nodeList.constructor.name);
// Convert to array using Array.from()
let array = Array.from(nodeList);
console.log('Array type:', array.constructor.name);
console.log('Array length:', array.length);
// Now we can use array methods
array.forEach((item, index) => {
item.style.backgroundColor = 'red';
item.textContent = `A${index + 1}`;
});
document.getElementById('output').innerHTML =
'<p>Used Array.from() - NodeList converted to array and styled</p>';
}
function useSpread() {
let nodeList = document.querySelectorAll('.sample');
// Convert using spread operator
let array = [...nodeList];
array.map((item, index) => {
item.style.backgroundColor = 'green';
item.textContent = `S${index + 1}`;
return item;
});
document.getElementById('output').innerHTML =
'<p>Used spread operator [...nodeList] - Array methods available</p>';
}
function resetColors() {
let nodeList = document.querySelectorAll('.sample');
Array.from(nodeList).forEach((item, index) => {
item.style.backgroundColor = 'blue';
item.textContent = index + 1;
});
document.getElementById('output').innerHTML = '';
}
</script>
</body>
</html>
Using Spread Operator
The spread operator provides a concise syntax for converting NodeLists:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spread Operator Example</title>
</head>
<body>
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<p class="text">Paragraph 3</p>
<div id="result"></div>
<script>
// Get all paragraphs
let paragraphs = document.querySelectorAll('p.text');
console.log('NodeList:', paragraphs);
// Convert to array using spread
let paragraphArray = [...paragraphs];
console.log('Array:', paragraphArray);
// Use array methods
let texts = paragraphArray.map(p => p.textContent);
console.log('Extracted texts:', texts);
document.getElementById('result').innerHTML =
'<strong>Converted texts:</strong> ' + texts.join(', ');
</script>
</body>
</html>
Comparison of Methods
| Method | Syntax | Browser Support | Readability |
|---|---|---|---|
Array.from() |
Array.from(nodeList) |
ES6+ (IE not supported) | Very clear |
| Spread Operator | [...nodeList] |
ES6+ (IE not supported) | Concise |
| Array.prototype.slice | [].slice.call(nodeList) |
All browsers | Less intuitive |
Why Convert NodeList to Array?
NodeLists have limited methods compared to arrays:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NodeList vs Array Methods</title>
</head>
<body>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div id="demo"></div>
<script>
let nodeList = document.querySelectorAll('.item');
let array = Array.from(nodeList);
// NodeList has limited methods
console.log('NodeList forEach available:', typeof nodeList.forEach);
console.log('NodeList map available:', typeof nodeList.map);
// Array has full method support
console.log('Array forEach available:', typeof array.forEach);
console.log('Array map available:', typeof array.map);
console.log('Array filter available:', typeof array.filter);
// Demonstrate array methods
let filteredArray = array.filter(item =>
item.textContent.includes('1') || item.textContent.includes('3')
);
let mappedTexts = filteredArray.map(item =>
item.textContent.toUpperCase()
);
document.getElementById('demo').innerHTML =
'<p>Filtered and mapped: ' + mappedTexts.join(', ') + '</p>';
</script>
</body>
</html>
Conclusion
Use Array.from() or the spread operator [...] to convert NodeLists to arrays for access to full array methods. Array.from() is more explicit and readable, while the spread operator is more concise.
Advertisements
