QuerySelectorAll and modern array functions

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 document.getElementBy[...].

For such functions, you expect a list of elements matching the requirement. Living in the JavaScript world, you may expect an Array to be returned. Once you have your elements returned, it would be great to process them using one of the handy Array functions such as map, reduce, filter or find.

Let’s take a look at the example code:

document.querySelectorAll('a').map(function(x){return x.href})

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?

The 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:

Array.from(document.querySelectorAll('a')).map(function(x){return x.href})

Simple as that.

An 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 for loop.

Leave a Reply

Your email address will not be published. Required fields are marked *