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.
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
Let's say we have a bunch of for-sale listings on an HTML page that we want to add event listeners to.
To do this, we'll need to select them with
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:
- Dom NodeList's sort of act like arrays, but lack a bunch of the cool array methods like map, reduce, filter, and more.
- 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 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.