Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  193] [ 1]  / answers: 1 / hits: 51015  / 11 Years ago, tue, february 26, 2013, 12:00:00

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?


More From » for-loop

 Answers
0

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

[#79988] Monday, February 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
devinjadong questions
Thu, Feb 17, 22, 00:00, 2 Years ago
Wed, Dec 8, 21, 00:00, 2 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Fri, Oct 18, 19, 00:00, 5 Years ago
;