forEach is not a function error with JavaScript array

前端 未结 11 578
梦毁少年i
梦毁少年i 2020-11-29 17:11

I\'m trying to make a simple loop:

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


        
11条回答
  •  青春惊慌失措
    2020-11-29 17:50

    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(child => {
        console.log(child)
    });
    

    or using spread operator:

    [...parent.children].forEach(function (child) {
        console.log(child)
    });
    

提交回复
热议问题