DEV Community

Discussion on: Why do you need to know about Array-like Objects?

Collapse
taufik_nurrohman profile image
Taufik Nurrohman

FYI:

// :(
document.getElementsByTagName('li').forEach(fn);

// :)
document.querySelectorAll('li').forEach(fn);
Enter fullscreen mode Exit fullscreen mode
Collapse
atapas profile image
Tapas Adhikary Author

Thanks Taufik for the note. Glad that, you got this into the discussion.

document.querySelectorAll('li').forEach(fn); Works

It is because, document.querySelectorAll('li') returns a NodeList, not HTMLCollection.

Here to note, both HTMLCollection and NodeList are Array-like objects. Both have a length property defining the number of items in the list (collection). Both provide an index (0, 1, 2, 3, 4, ...) to access each item like an array.

There is a difference though. You can loop through the node list and refer to its nodes like an array. You can not do the same for HTMLCollection. That is the reason forEach doesn't work in first case and works for second one.

However, you cannot use Array Methods, like valueOf(), push(), pop(), or join() on a node list.

When you try, document.querySelectorAll('li').pop(), you will get Uncaught TypeError: document.querySelectorAll(...).pop is not a function.

We can refer this for further info: w3schools.com/js/js_htmldom_nodeli...