The issue I want to address today is not only related to the
document.querySelectorAll but also to the range of DOM related functions such as
document.getElementByClassName or in general
Let’s take a look at the example code:
As a result, I expect to retrieve the Array of
href attributes for all links on the page. Unfortunately, it is not working, returning the error:
TypeError: document.querySelectorAll(...).map is not a function
so, how to handle DOM related lists?
document.queryselectorAll is returning a NodeList which is not an array. For
document.getElementBy[...], in most cases, we get HTMLCollection which also is not an array.
The solution to the problem here is rather easy. You can use the
Array.from() function, which creates an array from an array-like or iterable object. For the code above, the solution looks like this:
Simple as that.
Array.from() returns an Array on which you can call
map, or any other Array-related functions. Please note that as the result you will receive an Array, not the NodeList or HTMLCollection. If you wish to work on these source types, you have to use good old