JS .children Returns an Object, Want an Array (ES6) [duplicate] JS .children Returns an Object, Want an Array (ES6) [duplicate] arrays arrays

JS .children Returns an Object, Want an Array (ES6) [duplicate]


.map expects an array. You need to convert this array-like object (HTMLCollection) into a real array. There are several methods, but my 2 favorite are ES6 spread, and array from.

Array.from(document.getElementById('test').children).map

Or spreading

[...document.getElementById('test').children].map

If you don't want to use ES6, you can slice and force an array conversion, or [].slice.call(document.getElementById('test').children) I believe would also do a conversion.

As Patrick said in the comments: [].slice.call, not [].call. Might also want to mention the more wordy Array.prototype.slice.call since it doesn't initialize an unused empty array

The key here is that an HTMLCollection is an object, where map is an Array function.