代码网 logo
AI

document.getElementsByClassName('class').forEach 报错Uncaught TypeError: undefined is not a function

开开2021-09-17 19:28:20151

问题描述:通过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

广告