Why can't I use Array.forEach on a collection of Javascript elements? [duplicate] Why can't I use Array.forEach on a collection of Javascript elements? [duplicate] arrays arrays

Why can't I use Array.forEach on a collection of Javascript elements? [duplicate]


You can. You just can't use it like that, because there is no forEach property on the HTMLFormControlsCollection that form.elements gives you (which isn't an array).

Here's how you can use it anyway:

Array.prototype.forEach.call(form.elements, (element) => {    // ...});

Or on modern browsers you can make use of the fact that the underlying HTMLCollection is iterable even though it doesn't have forEach:

// `for-of`:for (const element of elements) {    // ...do something with `element`...}// Spreading into an array:[...elements].forEach((element) => {    // ...do something with `element`...});

That won't work on obsolete browsers like IE11 though.

There's also Array.from (needs a polyfill for obsolete browsers):

Array.from(elements).forEach((element) => {    // ...});

For details, see the "array-like" part of my answer here.


You cannot use forEach on HMTLCollection. forEach can only be used on `array.

Alternatives are, use lodash and do _.toArray(), which will convert the HTMLColelction to an array. After this, you can do normal array operations over it. Or, use ES6 spread and do forEach()

Like this,

var a = document.getElementsByTagName('div')[...a].forEach()


form.elements, document.getElementsByTagName, document.getElementsByClassName and document.querySelectorAll return a node list.

A node list is essentially an object that doesn't have any methods like an array.

If you wish to use the node list as an array you can use Array.from(NodeList) or the oldschool way of Array.prototype.slice.call(NodeList)

// es6const thingsNodeList = document.querySelectorAll('.thing')const thingsArray = Array.from(thingsNodeList)thingsArray.forEach(thing => console.log(thing.innerHTML))// es5var oldThingsNodeList = document.getElementsByClassName('thing')var oldThingsArray = Array.prototype.slice.call(oldThingsNodeList)thingsArray.forEach(function(thing){   console.log(thing.innerHTML) })
<div class="thing">one</div><div class="thing">two</div><div class="thing">three</div><div class="thing">four</div>