0

So I just learned that it makes a difference whether I use

document.querySelectorAll('selector')

or

document.getElementsByClassName('selector')

The latter cant be iterated over with .forEach. This is probably because the latter returns an array-like object, while the first one returns a nodelist.

Now I read that some browsers return an array-like object when using document.querySelectorAll('selector') https://www.w3schools.com/js/js_htmldom_nodelist.asp

I'm not even sure if this problem applies to me, since I'm using a webpack based framework which uses Babel7 to transpile my Code to ES2015. But I would like to make sure that my code works on as many browsers as possible, and therefore it would be nice to know if there is a JS method to retrieve elements from the DOM which makes sure of that.

And on a sidenote, could someone point me to the piece of documentation explaining lists in JS? I couldnt find much, only the doc about arrays. Is a list just an alias for an array in JS?

Narktor
  • 977
  • 14
  • 34
  • 2
    Possible duplicate of [JS: iterating over result of getElementsByClassName using Array.forEach](https://stackoverflow.com/questions/3871547/js-iterating-over-result-of-getelementsbyclassname-using-array-foreach) – MauriceNino Aug 13 '19 at 10:04
  • maybe you should take a look at [`Array.from()`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/from) – jonatjano Aug 13 '19 at 10:05
  • Also, there are no `Lists` in JavaScript per se. An array in JavaScript is kind of like a List/Stream in other Languages, so it is probably what you are looking for. – MauriceNino Aug 13 '19 at 10:05

1 Answers1

1

querySelectorAll returns a NodeList, and getElementsByClassName returns a HTMLCollection.

The recent development seems to be that all array methods were added to NodeLists, while the HTMLCollection did not change for years, so I'd try to work with NodeLists as they are up-to-date, and provide .forEach and others.

I'd write:

 for(const el of document.querySelectorAll('.some-class'))
    //...

But I would like to make sure that my code works on as many browsers as possible, and therefore it would be nice to know if there is a JS method to retrieve elements from the DOM which makes sure of that

For sure older browsers don't have newer features, no matter what new feature you use. However thats not your problem, Webpack handles that for you, just make sure to add the necessary polyfills.

And on a sidenote, could someone point me to the piece of documentation explaining lists in JS?

There ain't Lists in JS, there is just a coined term called arraylike objects, which are objects that contain numeric keys and that do have a .length, however they do not inherit from Array. For some reason NodeList and HTMLCollection are such arraylike objects.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151