getElementsByClassName 返回 HTMLCollection,而不是数组
在 JavaScript 中,document.getElementsByClassName 方法返回与指定匹配的 DOM 元素的集合类名。然而,这个集合不是一个数组,而是一个 HTMLCollection。
在现代浏览器(Firefox 3 及更高版本)中,Array.forEach 方法可以通过设置 this 与 HTMLCollection 一起使用forEach 函数的值传递给 HTMLCollection。操作方法如下:
var els = document.getElementsByClassName("myclass"); Array.prototype.forEach.call(els, function(el) { // Do something with the element }); // Or, in ES6+ [].forEach.call(els, (el) => { // Do something with the element });
使用 ES6 的更现代方法是使用 Array.from 将 HTMLCollection 转换为实际数组:
Array.from(els).forEach((el) => { // Do something with the element });
通过设置 this 值或者使用 Array.from,您可以使用 forEach 方法迭代 HTMLCollection,就好像它是一个数组一样。请注意,Internet Explorer 8 及更低版本等较旧的浏览器不支持此方法,并且将返回 NodeList 而不是 HTMLCollection。
以上是为什么 JavaScript 中 `getElementsByClassName` 不返回数组?的详细内容。更多信息请关注PHP中文网其他相关文章!