在 getElementsByClassName 的数组上使用 forEach 会导致“TypeError: undefined is not a function”

问题描述 投票:0回答:3

my JSFiddle 中,我只是尝试迭代一个元素数组。正如日志语句所证明的那样,该数组非空。然而,对

forEach
的调用给了我(不太有帮助)“未捕获
TypeError
undefined
不是函数”错误。

我一定是做了什么蠢事;我做错了什么?

我的代码:

var arr = document.getElementsByClassName('myClass');
console.log(arr);
console.log(arr[0]);
arr.forEach(function(v, i, a) {
  console.log(v);
});
.myClass {
  background-color: #FF0000;
}
<div class="myClass">Hello</div>

javascript foreach
3个回答
180
投票

那是因为

document.getElementsByClassName
返回一个 HTMLCollection,而不是一个数组。

幸运的是,它是一个“类似数组”的对象(这解释了为什么它被记录为一个对象,以及为什么你可以使用标准的

for
循环进行迭代),所以你可以这样做:

[].forEach.call(document.getElementsByClassName('myClass'), function(v,i,a) {})

使用 ES6(在现代浏览器或 Babel 上),您还可以使用

Array.from
从类似数组的对象构建数组:

Array.from(document.getElementsByClassName('myClass')).forEach( v=> {})

或将类似数组的对象展开到数组中:

[...document.getElementsByClassName('myClass')].forEach( v=> {})

11
投票

尝试一下它应该有效:

<html>
  <head>
    <style type="text/css">
    </style>
  </head>
  <body>
   <div class="myClass">Hello</div>
   <div class="myClass">Hello</div>

<script type="text/javascript">
    var arr = document.getElementsByClassName('myClass');
    console.log(arr);
    console.log(arr[0]);
    arr = [].slice.call(arr); //I have converted the HTML Collection an array
    arr.forEach(function(v,i,a) {
        console.log(v);
    });
</script>


<style type="text/css">
    .myClass {
    background-color: #FF0000;
}
</style>

  </body>
</html>

0
投票

如果您想要访问特定类的每个元素的 ID,您可以执行以下操作:

    Array.from(document.getElementsByClassName('myClass')).forEach(function(element) {
        console.log(element.id);
    });
© www.soinside.com 2019 - 2024. All rights reserved.