登录/注册
开开
9779
占位
8
占位
12
浏览量
占位
粉丝
占位
关注
document.getElementsByClassName('class').forEach 报错Uncaught TypeError: undefined is not a function
开开
2021-09-17 19:28:20 2021-09-17
144
0

问题描述:通过document.getElementsByClassName获取DOM对象,并对返回值通过forEach遍历,报错:Uncaught TypeError: undefined is not a function

代码:

var arr = document.getElementsByClassName('myClass');
arr.forEach(function(item) {
console.log(item);
});

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

解决办法:将获得的HTMLCollection转换成数组,有如下几种方法。

[].forEach.call(document.getElementsByClassName('myClass'), function(v) {
console.log(v);
})
Array.from(document.getElementsByClassName('myClass')).forEach(v=>{
console.log(v)
});
[...document.getElementsByClassName('myClass'))].forEach(v=>{
console.log(v)
});

原文: https://www.cnblogs.com/ming1025/p/13649635.html

暂无评论