简体   繁体   中英

How can I make sure I get a collection of HTML nodes/elements which I can use forEach on?

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?

querySelectorAll returns a NodeList , and getElementsByClassName returns a HTMLCollection .

The recent development seems to be that all array methods were added to NodeList s, while the HTMLCollection did not change for years, so I'd try to work with NodeList s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM