Using Array Methods with Nodelists

One of the differences between an Array and a nodelist is all of the methods that exist for any array, none of which exist for nodelists. Here we are going to look at how we can effectively cast the nodelist into an array so as to be able to use any of the array methods on our nodelist just as if the nodelist were an array.

One distinction that we do need to make is between nodelists and collections. What the DOM calls getElementsByTagName, getElementsByName etc used to be called a nodelist. At that time a nodelist was dynamic and would change automatically when the information in the page that matched the call changed. The introduction of the new querySelectorAll call which returns a static nodelist means that the dynamic references those other calls return are now referred to as collections.

Casting a nodelist to an array will have no effect on the subsequent processing except for making all the array methods available to use with the nodelist. Casting a collection to an array gives us a static array that will no longer reflect the current live content of the page if that has changed since the collection was first created. Most of the time this doesn't matter but if you don't need a dynamic collection then you are probably best off creating a static nodelist in the first place.

As a simple example of how to cast a nodelist into an array to use array methods on the nodelist let's imagine that we have a table in the HTML and we want to extract the text content of the first column of the body of the table and to create an array of that text. The array function for creating a new array whose content depends on applying the same processing to each element in the original array is map(). So if the rows in the body of the table were an array rather than a nodelist then we could apply the map() method to extract the text from the first cell of each.

By casting our nodelist into an array we can do exactly that. First we need to extract the rows from the body of the table into a nodelist:

var rows = document.querySelectorAll('tbody tr');

Next we cast the nodelist to an array so that we can use the map method to call a specified function for each entry in the nodelist:

var col1 = [], extractText);

All that remains is to define the extractText function so that it will extract the text of the first cell in the current row:

function extractText(row) {
return row.querySelector('td').textContent);

This technique of casting the nodelist to an array (or to be more accurate - using an array method and calling it on a nodelist instead of an array) can be used with any of the array methods in order to process a nodelist with that method.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow