在来自 getElementsByClassName 的数组上使用 forEvery 会导致“ TypeError: unDefinition 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>

100927 次浏览

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=>{

Try this it should work :

<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>

in the event that you want to access the ID of each element of a specific class you can do the following:

    Array.from(document.getElementsByClassName('myClass')).forEach(function(element) {
console.log(element.id);
});