forEach does not work with document.querySelectorAll(). The following, document.querySelectorAll('body').forEach( function ($node) { } ); Throws: Value undefined (result of expression document.querySelectorAll("body").forEach) is not object. Tried this today in the latest nightly.
This is not expected to work as querySelectorAll returns a StaticNodeList, not an Array. StaticNodeList does not have a forEach method. A work around would be to use Array.prototype.forEach.call. Richard, why did you expect this to work? Does it work in other implementations? Should we consider adding it?
Thanks for explaining that. It's a pretty common thing to do with JavaScript frameworks. Makes it easier to enumerate over elements. I use Dean Edwards's Base2... which allows this kind of traversal, and it seems like I've seen similar code in use with other more popular frameworks, but I'm not sure about that. Dean shows how document.querySelectorAll can be used with forEach here: http://dean.edwards.name/weblog/2007/03/yet-another/ Though, reading that again, he made that distinction clear too, so I understand why it isn't expected to work, but I think it'd be pretty useful. I use that all over the place in my apps, makes the code more readable and compact.
Unfortunately adding this to NodeList has proven difficult. Happy to reconsider if it gets standardized somehow.