Skip to content Skip to sidebar Skip to footer

Why Can't I Use Array.foreach On A Collection Of Javascript Elements?

I'm building an app with Babel/ES6. I want to disable all form elements for a view-only version of it, so I did this: let form = document.getElementById('application-form') let ele

Solution 1:

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.

Solution 2:

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()

Solution 3:

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) 
})
<divclass="thing">one</div><divclass="thing">two</div><divclass="thing">three</div><divclass="thing">four</div>

Post a Comment for "Why Can't I Use Array.foreach On A Collection Of Javascript Elements?"