1

What I want to know

I've heard that sometimes NodeLists need to be changed to Arrays to use forEach() method. What kind of situation do I have to do it in?


What I tried

I wrote this:

const items = document.querySelectorAll('.js-li');
const arrItems = Array.from(items);

items.forEach((v, i, a) => console.log(`${v} / ${i} / ${a}`));
arrItems.forEach((v, i, a) => console.log(`${v} / ${i} / ${a}`));
<ul>
  <li class="js-li">zero</li>
  <li class="js-li">one</li>
  <li class="js-li">two</li>
  <li class="js-li">three</li>
  <li class="js-li">four</li>
</ul>

But I couldn't understand the difference between with/without Array.from().

1

1 Answer 1

3

Look

NodeLists and Arrays are two different things because NodeLists are actually not a JavaScript API, but a browser API.

Things like querySelectorAll() and getElementsByTagName() aren’t JavaScript methods, they’re browser APIs that let you access DOM elements. You can then manipulate them with JavaScript.

NodeLists differ from Arrays in another meaningful way, too.

They are often live lists, meaning that if elements are removed or added to the DOM, the list updates automatically. querySelector() and querySelectorAll() return a static list (one that doesn’t update), but properties like .childNodes are live lists that will change as you manipulate the DOM (which can be a good or bad thing, depending on how you’re using it).

This is all made more confusing because arrays can contain nodes. And, there’s another, older type of list called an HTMLCollection that predates NodeLists, but is functionally similar (another article for another day).

The key way to think about NodeLists vs. Arrays: NodeLists are a language-agnostic way to access DOM elements, and Arrays are a JavaScript object you can use to contain collections of stuff.

They each have their own methods and properties, and you can convert a NodeList into an Array if you need to (but not the other way around).

Not the answer you're looking for? Browse other questions tagged or ask your own question.