forEach is not a function error with JavaScript ar

2019-01-21 10:10发布

I'm trying to make a simple loop:

const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
  console.log(child)
})

But I get the following error:

VM384:53 Uncaught TypeError: parent.children.forEach is not a function

Even though parent.children logs:

enter image description here

What could be the problem?

Note: Here's a JSFiddle.

10条回答
Ridiculous、
2楼-- · 2019-01-21 10:51

There is no need for the forEach, you can iterate using only the from's second parameter, like so:

let nodeList = [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]
Array.from(nodeList, child => {
  console.log(child)
});

查看更多
狗以群分
3楼-- · 2019-01-21 11:02

That's because parent.children is a NodeList, and it doesn't support the .forEach method (as NodeList is an array like structure but not an array), so try to call it by first converting it to array using

var children = [].slice.call(parent.children);
children.forEach(yourFunc);
查看更多
Ridiculous、
4楼-- · 2019-01-21 11:02

This has always worked for me

const someElement = document.querySelectorAll('.someElement');

  someElement.forEach((element) => {
    // Your code here
  });
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-21 11:05

parent.children is not an array. It is HTMLCollection and it does not have forEach method. You can convert it to the array first. For example in ES6:

Array.from(parent.children).forEach(function (child) {
    console.log(child)
});

or using spread operator:

[...parent.children].forEach(function (child) {
    console.log(child)
});
查看更多
可以哭但决不认输i
6楼-- · 2019-01-21 11:06

parent.children will return a node list, technically a html element Collection. That is an array like object, but not an array, so you cannot call array functions over it directly. At this context you can use Array.from() to convert that into a real array,

Array.from(parent.children).forEach(child => {
  console.log(child)
})
查看更多
够拽才男人
7楼-- · 2019-01-21 11:08

If you are trying to loop over a NodeList like this:

const allParagraphs = document.querySelectorAll("p");

I highly recommend loop it this way:

Array.prototype.forEach.call(allParagraphs , function(el) {
    // Write your code here
})

Personally, I've tried several ways but most of them didn't work as I wanted to loop over a NodeList, but this one works like a charm, give it a try!

The NodeList isn't an Array, but we treat it as an Array, using Array. So, you need to know that it is not supported in older browsers!

Need more information about NodeList? Please read its documentation on MDN.

查看更多
登录 后发表回答