Cannot Loop Through Array Like Object

I’m trying to get data from an array like object using foeach but it’s giving me the following error:

Uncaught TypeError: Cannot read property 'call' of undefined

The array like object contains children elements of a div but I do not know why the property is undefined. Please see my code here. Once inside jsFiddle, you can click the blue button and check the console log to see the error message. Thank you.

“children” is not an Array. That is HTMLCollection.

Hi @liagapi555, using forEach.call() (note the camel case BTW) is a way to apply array methods to array like objects such as your HTML collection; it works this way:

const nodes = document.getElementById('something').children

Array.prototype.forEach.call(nodes, node => {
  // do something with the node
})

A better way though is to just convert your object to an actual array from the first:

const nodes = Array.from(document.getElementById('something').children)

nodes.forEach(node => {
  // do something
})

Thanks for your help, your suggestion works great.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.