npmvue.js95% confidence\u2191 277

forEach is not a function error with JavaScript array

Full error message
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:

What could be the problem?

Note: Here's a JSFiddle.

First option: invoke forEach indirectly The parent.children is an Array like object. Use the following solution: const parent = this.el.parentElement; Array.prototype.forEach.call(parent.children, child => { console.log(child) }); The parent.children is NodeList type, which is an Array like object because: It contains the length property, which indicates the number of nodes Each node is a property value with numeric name, starting from 0: {0: NodeObject, 1: NodeObject, length: 2, ...} See more details in this article. Second option: use the iterable protocol parent.children is an HTMLCollection: which implements the iterable protocol. In an ES2015 environment, you can use the HTMLCollection with any construction that accepts iterables. Use HTMLCollection with the spread operatator: const parent = this.el.parentElement; [...parent.children].forEach(child => { console.log(child); }); Or with the for..of cycle (which is my preferred option): const parent = this.el.parentElement; for (const child of parent.children) { console.log(child); }

API access

Get this solution programmatically \u2014 free, no authentication.

curl https://depscope.dev/api/error/d78b406f7aa471c5d6b41ef37a1c5d7da560ec313bec8a15a23db46cb27a14c5
hash \u00b7 d78b406f7aa471c5d6b41ef37a1c5d7da560ec313bec8a15a23db46cb27a14c5
forEach is not a function error with JavaScript array — DepScope fix | DepScope