How can I make .querySelectorAll() or .forEach() work in Firefox?

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

I want to remove all elements with class sample.

This is working well in Chrome and Safari:

document.querySelectorAll('.sample').forEach(function(e) {     e.parentNode.removeChild(e); }); 

Here is the error I get in Firefox:

TypeError: document.querySelectorAll(...).forEach is not a function

回答1:

document.querySelectorAll returns a NodeList which is indexed like an array, but not an Array so you can't call the array methods on it.

You can use Array.from(nodeList) in ES6 or Array.prototype.slice.call(nodeList) for ES5

 Array.from(document.querySelectorAll('selector')).forEach(el => el) 


回答2:

You can also use a polyfill (see https://developer.mozilla.org/de/docs/Web/API/NodeList/forEach):

if (window.NodeList && !NodeList.prototype.forEach) {     NodeList.prototype.forEach = function (callback, thisArg) {         thisArg = thisArg || window;         for (var i = 0; i < this.length; i++) {             callback.call(thisArg, this[i], i, this);         }     }; } 

This adds the forEach method to the NodeList, if it is missing.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!