Here's my demo.
I'm trying to get the JavaScript forEach
method to work in Google Chrome.
Caniuse hasn't been much help. :(
Any help would be appreciated! Thanks!
Here's my demo.
I'm trying to get the JavaScript forEach
method to work in Google Chrome.
Caniuse hasn't been much help. :(
Any help would be appreciated! Thanks!
Share Improve this question edited May 8, 2012 at 5:29 Mithir 2,4233 gold badges27 silver badges40 bronze badges asked May 8, 2012 at 5:25 Web_DesignerWeb_Designer 74.6k93 gold badges209 silver badges266 bronze badges 2- Any particular reason not to use jQuery? performance? – Eran Medan Commented May 8, 2012 at 5:33
- @EranMedan My case is small, my pageload is fast, and I'd like to keep it that way. :) – Web_Designer Commented May 8, 2012 at 5:42
4 Answers
Reset to default 14Convert the NodeList to an array:
nodes = Array.prototype.slice.call(nodes);
Then you can use .forEach()
on it.
document.querySelectorAll
doesn't return array but a NodeList
object which has no method 'forEach'.
The error msg shows you that:
Object #<NodeList> has no method 'forEach'
Check this article, which explains this.
Just convert it using some modern JavaScript:
let paragraphs = Array.from(nodes)
paragraphs.forEach(paragraph => console.log(`This is the paragraph: ${paragraph}`);
Yes, you can call forEach
but on arrays.
In your case, the data may not be in an array, it may be an HTMLCollection
and that's why you are seeing this error, you can fix this by changing the data to Array
, like this:-
// HTMLCollection
const allJobs = document.getElementsByClassName('component_4d072');
// Array
const arrayAllJobs = [...allJobs];
// and now you can run
arrayAllJobs.forEach(jobs => console.log(jobs));