在my JSFiddle ,我只是想遍历一个元素数组。正如日志语句所证明的那样,该数组是非空的。然而,对 forEach
的调用给了我(不是很有帮助)“Uncaught TypeError
: undefined
is not a function”错误。
我一定是在做傻事;我做错了什么?
我的代码:
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>
最佳答案
那是因为 document.getElementsByClassName
返回一个 HTMLCollection ,不是数组。
幸运的是它是一个 "array-like" object (这解释了为什么它被记录为一个对象,以及为什么你可以用标准的 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=>{
关于javascript - 在 getElementsByClassName 的数组上使用 forEach 会导致 “TypeError: undefined is not a function”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24266313/