JS:使用 Array.forEach 迭代 getElementsByClassName 的结果 [英] JS: iterating over result of getElementsByClassName using Array.forEach
问题描述
我想遍历一些 DOM 元素,我这样做:
I want to iterate over some DOM elements, I'm doing this:
document.getElementsByClassName( "myclass" ).forEach( function(element, index, array) {
//do stuff
});
但我收到一个错误:
document.getElementsByClassName("myclass").forEach 不是函数
document.getElementsByClassName("myclass").forEach is not a function
我使用的是 Firefox 3,所以我知道 getElementsByClassName
和 Array.forEach
都存在.这工作正常:
I am using Firefox 3 so I know that both getElementsByClassName
and Array.forEach
are present. This works fine:
[2, 5, 9].forEach( function(element, index, array) {
//do stuff
});
getElementsByClassName
的结果是一个数组吗?如果不是,那是什么?
Is the result of getElementsByClassName
an Array? If not, what is it?
推荐答案
没有.正如 在 DOM4 中规定的,它是一个 HTMLCollection
(至少在现代浏览器中.旧浏览器返回一个NodeList
).
No. As specified in DOM4, it's an HTMLCollection
(in modern browsers, at least. Older browsers returned a NodeList
).
在所有现代浏览器(几乎任何其他 IE <= 8)中,您可以调用 Array 的 forEach
方法,将元素列表传递给它(例如 HTMLCollection
或 NodeList
) 作为 this
值:
In all modern browsers (pretty much anything other IE <= 8), you can call Array's forEach
method, passing it the list of elements (be it HTMLCollection
or NodeList
) as the this
value:
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) {...});
如果您很高兴能够使用 ES6(即您可以安全地忽略 Internet Explorer 或您使用的是 ES5 转译器),您可以使用 Array.from
:
If you're in the happy position of being able to use ES6 (i.e. you can safely ignore Internet Explorer or you're using an ES5 transpiler), you can use Array.from
:
Array.from(els).forEach((el) => {
// Do stuff here
console.log(el.tagName);
});
这篇关于JS:使用 Array.forEach 迭代 getElementsByClassName 的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!