0

I came across a little issue with JS in my project.

Basically I use this type of for loop for most arrays:

for (var item in array)
{
    // Do something with each "item"
}

Now that is working fine and dandy for the most part, but when I use it like this:

for (var element in someDOMelements)
{
    element.AddEventListener(...);
}

It is going to throw me an error, saying AddEventListener is not working However if I adjust the code to something like:

for (var i = 0; i < someDOMelements.length; i++)
{
    someDOMelements[i].AddEventListener(...);
}

It's working as it should. And just to rule it out I logged the array that the DOM elements are in before the loop and it correclty gave me a list (HTML Collection) of all the objects..

Is there anything specific going on here, that prevents me from manipulating DOM elements with these kind of for loops?

Cheers!

Cerbion
  • 109
  • 1
  • 2
  • 10
  • `for (var .. in ..)` iterates *object properties*. It "won't work" with an [HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) (as returned by `getElementsByTagName`); it marginally works for Arrays (fsvo, although the iterated values are the *indexes*) because the array indices are exposed as properties. – user2864740 May 03 '18 at 22:52
  • A modern alternative is to use `for...of` loop, but I'm not sure if it works with HTMLCollection. – Frax May 03 '18 at 22:55
  • About using `for ... in array`, I advise you to read this very carefully: https://stackoverflow.com/q/500504/1220550 – Peter B May 03 '18 at 22:55
  • Okay, well I am an avid user of foreach in PHP and I think loops of that sort make the code look way more clean and streamlined, and for example in the article that @peter-b pointed out, You can't really use `for(.. in ..)` for resized arrays, but I really only want to use it for iterating over every object that is actually defined in that array. Is there any good alternative (foreach loop in js)? I know some people like to add to the prototype, but I don't really like fiddling with important prototypes like arrays. – Cerbion May 04 '18 at 12:14

0 Answers0