在getElementsByClassName的数组上使用forEach会导致“TypeError:undefined不是函数” [英] Using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function”

查看:1070
本文介绍了在getElementsByClassName的数组上使用forEach会导致“TypeError:undefined不是函数”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSFiddle 中,我只是试图迭代一组元素。这个数组是非空的,正如日志所证明的那样。然而,对 forEach 的调用给了我(不那么有用)Uncaught TypeError undefined 不是函数错误。

我一定在做一些愚蠢的事情。我在做什么错了?



我的代码:

 

myClass {background-color:#FF0000;}

< div class =myClass> Hello< / div>

>解决方案

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



幸运的是 for loop),所以你可以这样做:

  []。 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 => {


In my JSFiddle, I’m simply trying to iterate over an array of elements. The array is non-empty, as the log statements prove. Yet the call to forEach gives me the (not so helpful) "Uncaught TypeError: undefined is not a function" error.

I must be doing something stupid; what am I doing wrong?

My code:

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>

解决方案

That's because document.getElementsByClassName returns a HTMLCollection, not an array.

Fortunately it's an "array-like" object (which explains why it's logged as if it was an object and why you can iterate with a standard for loop), so you can do this :

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

With ES6 (on modern browsers or with Babel), you may also use Array.from which builds arrays from array-like objects:

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

or spread the array-like object into an array:

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

这篇关于在getElementsByClassName的数组上使用forEach会导致“TypeError:undefined不是函数”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆