According its w3schools page (everyone's favorite resource, I know), the .children
property returns
A live HTMLCollection object, representing a collection of element nodes
This object can be looped over as if it were an array like so:
var elements = document.getElementById('test').children;
for (var i=0; i < elements.length; i++) {
console.log(elements[i]);
}
<div id="test">
<p>paragraph 1</p>
<p>paragraph 2</p>
<p>paragraph 3</p>
</div>
However attempting to use the .map
function throws an error:
var elements = document.getElementById('test').children;
var x = elements.map((element, index) => {
console.log(element);
});
<div id="test">
<p>paragraph 1</p>
<p>paragraph 2</p>
<p>paragraph 3</p>
</div>
Is there a better way to get an array of child DOM elements, or do I have to loop through the object and manually create an array in order to use array methods like .map()
? Note, I do not want to use jQuery. Thanks in advance.
.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.
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