兼容IE下无法forEach NodeList的bug

NodeList 对象是一个节点的集合,是由 Node.childNodesdocument.querySelectorAll返回的,实则是一个类数组对象

Although NodeList is not an Array, it is possible to iterate over it with forEach(). It can also be converted to a real Array using Array.from().
However, some older browsers have not implemented NodeList.forEach() nor Array.from(). This can be circumvented by using Array.prototype.forEach() — see this document's Example.

在主流浏览器和高版本IE下,可以直接使用forEach进行遍历,但对于IE11以下的版本,将无法执行遍历,下面提供一种方法对低版本IE做兼容

NodeList.prototype.forEach = Array.prototype.forEach;

直接在NodeList对象原型上指定forEach为Array的forEach,从而实现了NodeList的forEach遍历。

你可能感兴趣的:(兼容IE下无法forEach NodeList的bug)