I have a Because You can convert it to an array using 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. A cleaner and more modern way to convert a for example: This is an es6 feature. It will work on all modern browser. Element.children is not an array. It is an object called an To loop through it, you'll have to convert it into an array, which you can do using Array.prototype.slice: If you need a clean approach with a lightweight npm module to resolve above issue, please check this out https://www.npmjs.com/package/foreach-array Ex: For your scenario it is You can also do this: And after this you can call forEach on your collection: The best and most secure way would be actually to only add forEach in cases when it doesn't already exist:
.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.Array.prototype.slice:var children = [].slice.call(document.getElementById(...).children);
var children = Array.from(document.getElementById(...).children);
HTMLCollection like .children to an array to use forEach() (or map(), etc.) is to use the spread synthax ... in an array [].var children = [...document.getElementById('x').children];
[...document.getElementById('x').children].forEach(child => console.log(child))
[...document.getElementById('niceParent').children].forEach(child => console.log(child.textContent))<div id="niceParent">
<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
</div>HTMLCollection. These do not have an array’s methods (though they do have the length property).var children = Array.prototype.slice.call(document.getElementById("niceParent").children);
children.forEach(…);
import each from 'foreach-array';
const array = ['First Name', 'Last Name', 'Country'];
each(array, (value, index, array) => {
console.log(index + ': ' + value);
});
// Console log output will be:
// 0: First Name
// 1: Last Name
// 2: Country
document.getElementById("niceParent").children instead of array in the above exampleNodeList.prototype.forEach = HTMLCollection.prototype.forEach = Array.prototype.forEach;
document.getElementById("niceParent").children.forEach(...)
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
if (window.HTMLCollection && !HTMLCollection.prototype.forEach) {
HTMLCollection.prototype.forEach = Array.prototype.forEach;
}