Javascript对象forEach不是一个函数

Javascript Object forEach is not a function

本文关键字:一个 函数 对象 forEach Javascript      更新时间:2023-09-26

嗨,我试图访问选定元素的子节点,但浏览器告诉我该对象没有foreach函数。我应该怎么做才能访问子元素呢?我不想用jquery,我想用原生的,作为实验的目的。

下面是我的代码:

var el = document.querySelector('ol');
el.children.forEach(function(childEl) {
  console.log(childEl);
})
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <ol contenteditable oninput="">
    <li>press enter</li>
  </ol>
</body>
</html>

节点。children是dom集合,不是一个真正的数组,所以它没有像forEach这样的数组方法(也需要修复这种情况)。

一个常用的解决方案是调用数组方法将上下文作为html集合

var el = document.querySelector('ol');
[].forEach.call(el.children, function(childEl) {
  console.log(childEl);
})
  <ol contenteditable oninput="">
    <li>press enter</li>
  </ol>


另一种方法(类似)是首先将集合转换为数组(使用array .slice()),然后在其上调用数组方法

var el = document.querySelector('ol'),
  array = [].slice.call(el.children);
array.forEach(function(childEl) {
  console.log(childEl);
})
<ol contenteditable oninput="">
  <li>press enter</li>
</ol>