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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With