最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Does the JavaScript method array.forEach work in Chrome? - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

4 Answers 4

Reset to default 14

Convert 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));


发布评论

评论列表(0)

  1. 暂无评论