I have a <div>
with some child <div>
in it. E.g.
<div id="niceParent"> <div></div> <div></div> <div></div> <div></div> </div>
I tried to loop through them with the forEach
function, because I thought that document.getElementById("niceParent").children
is an array, as I can access the elements with
console.log(document.getElementById("niceParent").children[1]); console.log(document.getElementById("niceParent").children[2]); console.log(document.getElementById("niceParent").children[3]); console.log(document.getElementById("niceParent").children[4]);
Hence I tried
document.getElementById("niceParent").children.forEach(function(entry) { console.log(entry); });
which is not working. I get
TypeError: document.getElementById(...).children.forEach is not a function
As a workaround I also tried it with a—much more complicated—for..in
loop:
for (var i in document.getElementById("niceParent").children) { if (document.getElementById("niceParent").children[i].nodeType == 1) console.log(document.getElementById("niceParent").children[i]); }
which worked as expected.
Why?
The "forEach is not a function" error occurs when we call the forEach() method on a value that is not of type array, Map , or Set . To solve the error, make sure to only call the forEach method on arrays, Map or Set objects. Copied!
As always, the choice between map() and forEach() will depend on your use case. If you plan to change, alternate, or use the data, you should pick map() , because it returns a new array with the transformed data. But, if you won't need the returned array, don't use map() - instead use forEach() or even a for loop.
The main difference between map and forEach is that the map method returns a new array by applying the callback function on each element of an array, while the forEach method doesn't return anything. You can use the forEach method to mutate the source array, but this isn't really the way it's meant to be used.
Even though using return inside the callback of a forEach() loop would halt execution for the current iteration and move on to the next item in the loop, you should not use it to mimic the functionality of continue .
Because .children
contains an HTMLCollection
[MDN], not an array. An HTMLCollection
object is an array-like object, which exposes a .length
property and has numeric properties, just like arrays, but it does not inherit from Array.prototype
and thus is not an array.
You can convert it to an array using Array.prototype.slice
:
var children = [].slice.call(document.getElementById(...).children);
ECMAScript 6 introduces a new API for converting iterators and array-like objects to real arrays: Array.from
[MDN]. Use that if possible since it makes the intent much clearer.
var children = Array.from(document.getElementById(...).children);
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