getElementsByClassName使用forEach会报错。
阿西,记性不好真是头疼,Array.prototype.forEach.call(els, function(el) {}
就这一行代码总是记不住……
每次遇到这个问题都得百度,索性做个笔记水一水。
这行代码抄袭来源:https://www.it1352.com/769506.html
原文截取如下:
JS:使用Array.forEach遍历getElementsByClassName的结果(JS: iterating over result of getElementsByClassName using Array.forEach)
var els = document.getElementsByClassName("myclass");
Array.prototype.forEach.call(els, function(el) {
// Do stuff here
console.log(el.tagName);
});
// Or
[].forEach.call(els, function (el) {...});
为了不只是搬运工,小编整理之余稍稍解释下原因。
使用如下代码:
let els = document.getElementsByClassName('line-item')
console.log(els)
然后来控制台一观,内容如下:
HTMLCollection(3) [div#xx.line-item, div#cc.line-item, div#vv.line-item, xx: div#xx.line-item, cc: div#cc.line-item, vv: div#vv.line-item]
length: 3
0: div#xx.line-item
align: ""
title: ""
lang: ""
translate: true
dir: ""
hidden: false
accessKey: ""
draggable: false
spellcheck: true
autocapitalize: ""
contentEditable: "inherit"
isContentEditable: false
inputMode: ""
offsetParent: body
offsetTop: 480
offsetLeft: 90
offsetWidth: 613
原来如此,使用getElementsByClassName获取到的这玩意他不是个数组,是个HTMLCollection
HTMLCollection 这玩意又是啥呢?
我们看看w3school文档内容:
HTMLCollection 是一个接口,表示 HTML 元素的集合,它提供了可以遍历列表的方法和属性。
HTML DOM 中的 HTMLCollection 是“活”的;如果基本的文档改变时,那些改变通过所有 HTMLCollection 对象会立即显示出来。
下面的每个项目(以及它们指定的属性)都返回 HTMLCollection:
- Document (images, applets, links, forms, anchors)
- form (elements)
- map (areas)
- select (options)
- table (rows, tBodies)
- tableSection (rows)
- row (cells)
HTMLDocument 接口的许多属性都是 HTMLCollection 对象,它提供了访问诸如表单、图像和链接等文档元素的便捷方式。form.elements 和 select.options 都是 HTMLCollection 对象。HTMLCollection 还提供了遍历 Table 的各行以及 TableRow 的各个单元格的一种方便方法。
在上面已经提到了,HTMLCollection 对象是带有方法的 HTML 元素的集合,用它可以通过元素在文档中的位置或它们的 id 属性、name 属性获取元素。在 JavaScript 中,HTMLCollection 对象的行为和只读数组一样,可以使用 JavaScript 的方括号,通过编号或名称索引一个 HTMLCollection 对象,而不必调用 item() 方法和 namedItem() 方法。
HTMLCollection 对象是只读的,不能给它添加新元素,即使采用 JavaScript 数组语法也是如此。
HTMLCollection 对象和 NodeList 对象很相似,但前者可能既能用名称索引也能用数字索引。
看过w3c文档,发现这玩意更像个对象,所以不能直接用forEach,得适当做个转化。