In Firefox, your for/in iteration would return these items (all the iterable properties of the object): now you can see why you want to use for (var i = 0 i < list.length i++) instead so you just get 0, 1 and 2 in your iteration.Įvolution of Browser Support for NodeList and HTMLCollection iterationįollowing below is an evolution of how browsers have evolved through the time period 2015-2018 giving you additional ways to iterate. See for why you can't iterate an HTMLCollection with for/in. The for/in iteration simply won't work for an HTMLCollection. I just tried this in Chrome and iterating it the way you were iterating it will retrieve the items in the list (indexes 0, 1, 2, etc.), but also will retrieve the length and item properties. And, guess what, an HTMLCollection or nodeList object can both have other properties that will be returned with a for/in iteration. While it may appear to work for an array (returning array elements or pseudo-array elements), it can also return other properties of the object that are not what you are expecting from the array-like elements. That means it will return all iterable properties of an object. To include older browsers (including things like IE), this will work everywhere: var list = document.getElementsB圜lassName("events") Ĭonsole.log(list.id) //second console outputĮxplanation For Why You Should Not Use for/inįor/in is meant for iterating the properties of an object. Here's an example: var list = document.getElementsB圜lassName("events") The reasons to avoid it are described below.Īll recent versions of modern browsers (Safari, Firefox, Chrome, Edge) all support for/of iteration on DOM lists such nodeList or HTMLCollection. But, you should not be doing this with for/in in the first place.ĭo not ever use for/in to iterate a nodeList or an HTMLCollection. So, to get the value from the pseudo-array, you'd have to do list and to get the id, you'd do list.id. In response to the original question, you are using for/in incorrectly.
0 Comments
Leave a Reply. |