DEV Community

Discussion on: 5 Wonderful Javascript Tricks

Collapse
 
gilfewster profile image
Gil Fewster

Nice article, Connor.

Just a quick note for querySelectorAll, which can trip up developers when they first begin to use it.

querySelectorAll(target) doesn't return an Array, it returns an array-like object called NodeList. Superficially, the two look the same -- both have length properties, both can be iterated with for & forEach loops, and both allow you to access individual items using square bracket notation.

But NodeList does not have a number of methods that we routinely use on Arrays, including:

  • Push/Pop/Shift/Unshift
  • Splice/Slice
  • Join
  • Sort/Filter/Map/Reduce

Attempting to use these methods directly on an object return from querySelectorAll() will generate an error.

Happily, you can convert a NodeList into an Array using the Array.from() method.

const paras = document.querySelectorAll("p");
const paraLengths = paras.map(para => para.innerText.length);
//  error: paras.map is not a function"
const parasArray = Array.from(document.querySelectorAll("p"));
const paraLengths = parasArray.map(para => para.innerText.length);
// success -- paraLengths array contains the number of characters in each paragraph.

More info about NodeList on MDN WebDocs