Practical ES6: Creating Arrays Of Dom Nodes

You probably know how to select a group of elements using document.querySelectorAll(), and if you do, you know how messy it is to work with the newly selected dom nodes.

That said, since ES6 there has been a super simple and concise way to do this which this article will explore.

Prerequisites

there are a few skills you should have before reading this post...

  • A basic understanding of HTML, JS, and the Document Object Model (or DOM for short)
  • Basic understanding of the Rest operator introduced in ES6

The Problem

Let's say we have a bunch of for-sale listings on an HTML page that we want to add event listeners to.

example of html body with listing divs

To do this, we'll need to select them with document.querySelectorAll(div.listing). After doing this, we realize that instead of returning a standard javascript array of elements, document.querySelectorAll() returns something called a Dom NodeList.

This is a problem for a number of reasons, but for the sake of keeping it simple this post will focus on two:

  1. Dom NodeList's sort of act like arrays, but lack a bunch of the cool array methods like map, reduce, filter, and more.
  2. They're rarely used anywhere besides by browser functions like document.querySelectorAll, which makes compatibility with frameworks or other libraries a concern.

For these reasons alone, it would make sense to convert the list of dom items into something more common, like an Array...

The Old Solution

In the past, to convert Dom NodeList objects to arrays you would have to write some pretty inconcise, fragile code.

the pre-es6 way to convert a dom NodeList into an Array

The New Solution

Since ES6 introduced the spread operator, we've been able to compress all that code down to a concise and readable one-liner.

the post-es6 way to convert a dom NodeList into an Array