先上下面这段代码:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
会报错:Uncaught TypeError: parent.children.forEach is not a function
解决办法一:

const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
  console.log(child)
});

解决办法二:

# 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);
}

解决办法四:

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

解决办法五:

const children = parent.children;
for (var i = 0; i < children.length; i++){
    console.log(children[i]);
}
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐