我想要移除所有带有 sample
类的元素。
在 Chrome 和 Safari 中这个操作很有效:
document.querySelectorAll('.sample').forEach(function(e) {
e.parentNode.removeChild(e);
});
这是我在Firefox中遇到的错误:
类型错误:document.querySelectorAll(...).forEach不是一个函数
我想要移除所有带有 sample
类的元素。
在 Chrome 和 Safari 中这个操作很有效:
document.querySelectorAll('.sample').forEach(function(e) {
e.parentNode.removeChild(e);
});
这是我在Firefox中遇到的错误:
类型错误:document.querySelectorAll(...).forEach不是一个函数
document.querySelectorAll
返回的是类似数组索引的 NodeList,但不是 Array,因此您不能对其调用数组方法。
您可以在 ES6 中使用 Array.from(nodeList)
或在 ES5 中使用 Array.prototype.slice.call(nodeList)
Array.from(document.querySelectorAll('selector')).forEach(el => el)
forEach
方法,但这不是标准的,所以不能依赖它。 - synthet1cArray.from(document.querySelectorAll('.sample')).forEach(function(e) { e.parentNode.removeChild(e); });
- twharmon我刚在Firefox 71中使用.forEach
测试了document.querySelectorAll('.element')
,它可以正常工作。
CanIUse显示自2016年底FF 50版本以来就已经支持.forEach
: https://caniuse.com/#search=forEach
旧版本的FF只占有0.25%的市场份额,因此使用.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);
}
};
}
document.querySelectorAll('.sample')
返回一个Array
吗? - Anson