如何让.querySelectorAll()或.forEach()在Firefox中工作?

13

我想要移除所有带有 sample 类的元素。

在 Chrome 和 Safari 中这个操作很有效:

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

这是我在Firefox中遇到的错误:

类型错误:document.querySelectorAll(...).forEach不是一个函数


document.querySelectorAll('.sample') 返回一个 Array 吗? - Anson
3个回答

29

document.querySelectorAll 返回的是类似数组索引的 NodeList,但不是 Array,因此您不能对其调用数组方法。

您可以在 ES6 中使用 Array.from(nodeList) 或在 ES5 中使用 Array.prototype.slice.call(nodeList)

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

3
他们已经在他们的NodeList上实现了forEach方法,但这不是标准的,所以不能依赖它。 - synthet1c
这个可以用: Array.from(document.querySelectorAll('.sample')).forEach(function(e) { e.parentNode.removeChild(e); }); - twharmon
不幸的是,在前端开发中,我们只能按照最差的浏览器支持特性的速度前进。https://developer.mozilla.org/en/docs/Web/API/NodeList#Browser_compatibility - synthet1c
1
有人可以告诉我 forEach(el => {}) 和 forEach(function(){}) 之间有什么区别吗? - Yasir Ijaz

3

我刚在Firefox 71中使用.forEach测试了document.querySelectorAll('.element'),它可以正常工作。

CanIUse显示自2016年底FF 50版本以来就已经支持.forEach: https://caniuse.com/#search=forEach

旧版本的FF只占有0.25%的市场份额,因此使用.forEach应该是安全的。


1
你也可以使用 polyfill(请参见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);
        }
    };
}

如果NodeList缺少forEach方法,则会添加该方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接