对getElementsByClassName中的数组使用forEach会导致“TypeError: undefined
Using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function”
在我的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>
这是因为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=>{
试一下,它应该可以工作:
<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>
如果您想要访问特定类的每个元素的ID,您可以执行以下操作:
Array.from(document.getElementsByClassName('myClass')).forEach(function(element) {
console.log(element.id);
});
相关文章:
- Uncaught TypeError:undefined不是函数-ember js
- TypeError:undefined不是对象(正在评估'newWindow.focus')
- 尝试使用.ninnerHTMLlog打印数据,获取错误Uncaught TypeError:undefined不是函数
- Jquery,Uncaught TypeError:undefined不是函数
- Ember cli Uncatch TypeError: undefined 不是函数
- Infragistics igGrid Uncatch TypeError: undefined 不是一个函数
- Karma+PhantomJS TypeError:undefined不是对象(正在评估scope.jjackpot)
- TypeError:undefined不是使用d3.map的对象
- TypeError:undefined不是对象(正在评估'this.props')-React Nati
- 'TypeError:undefined不是函数'使用Protractor
- TypeError:undefined不是node.js/express.js中的函数
- 引用 Object.prototype.toString.call 导致“TypeError: undefined 不是
- uncatch TypeError: undefined 不是 datepair(); 的函数(匿名函数)
- AngularJS:“;TypeError:undefined不是函数“”;使用routeProvider
- $resource.get给出“;TypeError:undefined不是函数;
- Javascript:uncatch TypeError:undefined不是一个函数
- TypeError: undefined 不是一个函数(评估 'document.getsElementsByC
- TypeError:undefined 不是对象 - Safari 和 IE
- TypeError:undefined不是一个对象(评估'c.trigger')
- AngularJS:TypeError: undefined 不是具有链式选择的函数