inostia inostia - 1 year ago 91
Javascript Question

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 elements = form.elements

I expected to be able to do this, instead of using a regular old
loop (which did work):

elements.forEach((el) => {
el.disabled = true

but I got
TypeError: elements.forEach is not a function

The strange thing is if I
in the Chrome dev console it exactly like an array with a bunch of
objects. It doesn't display with the
notation for objects, and all of the keys are integers. I'm thinking it's some sort of pseudo array, but I wouldn't even know how to find that out.

EDIT: short answer it's not an array it's an HTMLCollection. see Why doesn't nodelist have forEach?

Answer Source

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:, function(element) {
    // ...

Or you may be able to use spread notation:

[...elements].forEach(function(element) {
    // ...

...but note that it relies on the HTMLFormControlsCollection implementation in the browser being iterable.

Or alternately Array.from (you'd need a polyfill for it, but you tagged ES2015, so...):

Array.from(elements).forEach(function(element) {
    // ...

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download