首页 >web前端 >js教程 >为什么 JavaScript 中 `getElementsByClassName` 不返回数组?

为什么 JavaScript 中 `getElementsByClassName` 不返回数组?

Linda Hamilton
Linda Hamilton原创
2024-12-06 12:23:15768浏览

Why Doesn't `getElementsByClassName` Return an Array in JavaScript?

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn