How can I make .querySelectorAll() or .forEach() w

2020-02-11 02:59发布

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

3条回答
做自己的国王
2楼-- · 2020-02-11 03:05

I've just tested document.querySelectorAll('.element') with .forEach in Firefox 71, and it worked.

CanIUse shows that it's been supported in FF, since version 50 (late 2016): https://caniuse.com/#search=forEach

Older versions of FF have a 0.25% marketshare, so .forEach should be safe to use.

查看更多
孤傲高冷的网名
3楼-- · 2020-02-11 03:17

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)
查看更多
倾城 Initia
4楼-- · 2020-02-11 03:26

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.

查看更多
登录 后发表回答