JS:使用Array.forEach遍历getElementsByClassName的结果(JS: iterating over result of getElementsByClassName using Array.forEach)

1462 IT屋

I want to iterate over some DOM elements, I'm doing this:

document.getElementsByClassName( "myclass" ).forEach( function(element, index, array) {
  //do stuff
});

but I get an error: document.getElementsByClassName("myclass").forEach is not a function

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
});

Is the result of getElementsByClassName an Array? If not, what is it?

解决方案

No. As specified in DOM4, it's an HTMLCollection (in modern browsers, at least. Older browsers returned a NodeList).

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) {...});


$ b
  document.getElementsByClassName("myclass")我想迭代一些DOM元素,我这样做: .forEach(function(element,index,array){
// do stuff
});


但是我得到一个错误:document.getElementsByClassName("myclass")forEach不是函数< / p>

我使用Firefox 3,所以我知道 getElementsByClassName 和 Array.forEach 存在。这工作正常:

$ $ p $ [2,5,9] .forEach(function(element,index,array){
//做东西
});


结果是 getElementsByClassName 一个数组?如果不是,那是什么?

解决方案

作为DOM4中指定的 ,它是 HTMLCollection (在现代浏览器中,至少老版本的浏览器返回了 NodeList ) 。在所有的现代浏览器(几乎任何其他的IE <= 8)中,你可以调用Array的 forEach 。 $ b

方法,将它作为这个元素的列表(它是 HTMLCollection 或 NodeList ) value:

  var els = document.getElementsByClassName("myclass"); 

Array.prototype.forEach.call(els,function(el){
//在这里做的事
console.log(el.tagName);
} );

//或
[] .forEach.call(els,function(el){...});

本文地址:IT屋 » JS:使用Array.forEach遍历getElementsByClassName的结果