DEV Community

Colt Borg
Colt Borg

Posted on • Originally published at coltborg.com on

Make node list into an array

Most of the time when I'm coding with node lists, I want to iterate through each of them and preform some action. My first thought is, "Node lists are _like_ arrays, I should be able to use the array methods like .map() or .filter() right?" 🤔

But every time it backfires because Node lists are actually objects.

const nodeArray = document.querySelectorAll('p');

nodeArray.map(node =\> console.log(node); // ❗️TypeError: nodeArray.map is not a function

To quickly fix this, I could either use the .forEach() method instead of .map().

const nodeArray = document.querySelectorAll('p');

nodeArray.forEach(node =\> console.log(node); // ✅ That works!

Or I could quickly turn the node list into an array using the spread operator.

const nodeArray = document.querySelectorAll('p');
const realArray = [...nodeArray];

realArray.map(node =\> console.log(node);
// ✅ That works!

Top comments (0)