This question already has answers here:
Closed 3 years ago.
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 for
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 console.log(elements)
in the Chrome dev console it exactly like an array with a bunch of input
objects. It doesn't display with the Object
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?
*UPDATE*
Per this answer, nodelist
now has the forEach
method!
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, 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.
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)
// es6
const thingsNodeList = document.querySelectorAll('.thing')
const thingsArray = Array.from(thingsNodeList)
thingsArray.forEach(thing => console.log(thing.innerHTML))
// es5
var 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>