最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeList.prototype.forEach = Array.prototype.forEach; - Stack Overflow

programmeradmin1浏览0评论

Do you see any problems with the following:

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

Normally forEach is just a property of arrays, but by setting it as a property of all NodeLists as well, there's no need to convert a NodeList to an array before you can loop through its nodes with forEach.

Do you see any problems with the following:

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

Normally forEach is just a property of arrays, but by setting it as a property of all NodeLists as well, there's no need to convert a NodeList to an array before you can loop through its nodes with forEach.

Share Improve this question asked Mar 7, 2013 at 9:21 Web_DesignerWeb_Designer 74.6k93 gold badges209 silver badges266 bronze badges 2
  • I liked this idea.. Waiting if others point out any problems in it. – Salman Commented Mar 7, 2013 at 9:28
  • Check out NodeList.js – Edwin Reynoso Commented Aug 8, 2015 at 13:52
Add a comment  | 

4 Answers 4

Reset to default 7

It's often not a good idea to extend the functionality of DOM through prototypes, especially in older versions of IE (article).

However, you can simply use Array.prototype.forEach even without adding it to the prototype chain or converting your NodeList into an array:

var list = document.querySelectorAll(".some.query");
Array.prototype.forEach.call(list, function(el){ /* ... */ });

/* or */
var forEach = function(ctn, callback){
    return Array.prototype.forEach.call(ctn, callback);
}
forEach(list, function(el){ /* ... */ });

See also MDN: Why can't I use forEach or map on a NodeList.

If you're working on a library that will be used by other people then it's not a good idea to do this.

If it's just your own code (i.e.. a website) then I guess it's no big deal. You should probably guard it though because in the future browsers will support NodeList.prototype.forEach natively (Chrome does already).

if (!NodeList.prototype.forEach) {
  NodeList.prototype.forEach = Array.prototype.forEach;
}

As Zeta mentioned, it would be better to use a convenience function. This version, however, will allow you to give it context.

var forEach = function(list, callback, context){
  return Array.prototype.forEach.call(list, callback, context);
};

NodeList.prototype.forEach() is now available in most browsers: https://developer.mozilla.org/fr/docs/Web/API/NodeList/forEach

Browser compatibility table: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach#Browser_Compatibility

发布评论

评论列表(0)

  1. 暂无评论