Make node list into an array
Colt Borg
Posted on December 15, 2019
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!
💖 💪 🙅 🚩
Colt Borg
Posted on December 15, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
react Axios NPM Package: A Beginner's Guide to Installing and Making HTTP Requests
November 30, 2024
webdev Adding Interactive Charts and Graphs to Tailwind CSS Admin Templates: A Step-by-Step Guide
November 30, 2024