在getElementsByClassName的数组上使用forEach会导致“TypeError:undefined不是函数” [英] Using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function”
问题描述
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屋!