This was one of the various questions that bugged me when I started learning Javascript. I could use a .forEach() loop on a NodeList but could not use other array methods such as .map(), .filter(), etc. What was the big deal?
Let's take a look at this block of code.
<div class="divs">
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
</div>
<script>
const divs = document.querySelectorAll('.div');
console.log(divs);
</script>
To get all the divs with a class of 'div', I use the document method of querySelectorAll(). This, in turn, returns an array like-list of 'divs' along with some array properties such as length as shown in the image below.
So basically, why does it give the error below when I try to run array methods such as .map()?
const individualDiv = divs.map(div => div);
console.log(individualDiv);
This is due to the fact that a NodeList may look and behave like an array but it does not have access to all array properties and methods.
In order to utilize the array properties and methods, we will need to convert it to an array. One way to do so is to use the Array.from() method.
const divs = document.querySelectorAll('.div');
let divArr = Array.from(divs);
If you prefer ES6 methods, the spread operator is a really simple way of converting it to an array.
let divArr = [...document.querySelectorAll('.div')]
And voila... array methods are good to go on any of the two above. If you would like to delve more into this subject, the MDN documentation is a great place to start π.
Top comments (0)