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

荒凉一梦 提交于 2019-11-29 13:50:17
T.J. Crowder

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!