Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 838
twharmon Avatar asked Dec 09 '16 06:12

twharmon


People also ask

Can you use forEach on querySelectorAll?

Since nodeList selected by querySelectorAll has an array-like structure so you can directly apply forEach method with it and pass element as the first element in the callback function.

Why querySelectorAll not working?

Originally Answered: Why is my querySelectorAll() method not working ? The reason is that you try to access DOM elements before they are part of the DOM. There is no reason to use the querySelector at all unless you have a table already you want to modify.

How do I access querySelectorAll?

The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.


1 Answers

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.

like image 185
Qasim Avatar answered Nov 01 '22 18:11

Qasim