DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!