可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.