- 在使用document.getElementsByTagName('li')获取所有标签的DOM元素使用forEach遍历元素时报错: Uncaught TypeError: lis.forEach is not a function at nodeList.html:17
说明DOM的类数组没有forEach方法,使用用getElementsByTagName('li')获取到的为HTMLCollection[],如get方法:- getElementsByTagName
- getElementsByClassName
- getElementsByName
返回类型 HTMLCollection[]。
如query方法:
- querySelectorAll
返回类型NodeList[] 上述两种方法获取dom类数组,都是没有forEach方法的,所有才会出现上面的一幕。
但如我们又想用forEach进行遍历怎样处理?既然forEach是Array的才有的方法,那我们就将dom类数组转换成数组。
- 方式1:将HTMLCollection[]或NodeList[]用Array原型方法slice转换成数组,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
</head>
<body>
<ul>
<li>01</li>
<li>02</li>
<li>03</li>
</ul>
<script>
const lis = document.getElementsByTagName('li');
const liArr0 = Array.prototype.slice.call(lis, 0);
liArr0.forEach(li => {
console.log(li);
})
</script>
</body>
</html>
- 方式2:用ES6中Array.from方法将HTMLCollection[]或NodeList[]转成数组,代码如下:
const liArr = Array.from(lis);
liArr.forEach(li => {
console.log(li);
})
- 方式3:只直用Array中的原型方法forEach,并用HTMLCollection[]或NodeList[]用call替换当前this,代码如下:
Array.prototype.forEach.call(lis, (val) => { console.log(val); })
- 最后如用jQuery,可用.each(),代码如下:
$('li').each((idx, li) => {
console.log(idx, li);
});
$.each(lis01, (idx, li) => {
console.log(idx, li);
})