Skip to content Skip to sidebar Skip to footer

Javascript Foreach On Nodelist

Consider the following code: var els = document.querySelectorAll('.myClassName'); Array.prototype.forEach.call(els, function(el) { console.log(el.id); }); The var els contains

Solution 1:

...and forEach applies on arrays only right?

Nope. Array.prototype.forEach is intentionally generic, it can be applied to any object that is array-like. From the spec:

NOTE2: The forEach function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method.

The spec clearly lays out what properties and/or methods will be used during the processing of forEach; as long as the object referenced via this during the call has those, forEach can be used on that object. That's why using forEach.call like that works: The call method on function objects (forEach is a function object) calls the function using the first argument you give call as this during the call, and passing along the following arguments as the arguments to the original function. So Array.prototype.forEach.call(x, y) calls forEach with this set to x and with the first argument set to y. forEach doesn't care about the type of this, just that it has the relevant properties and methods as described in the specification's algorithm for it.

Most of the Array.prototype methods are like that, and indeed many others on the other standard prototypes.


Side note: The NodeList returned by querySelectorAll recently became iterable on modern browsers, whcih means: 1.  It works with ES2015+'s for-of, and 2. It has forEach natively now. (On modern browsers.)

Post a Comment for "Javascript Foreach On Nodelist"