Home >Web Front-end >JS Tutorial >How to Correctly Iterate Through HTMLCollection Elements and Retrieve Their IDs?
You're attempting to iterate through an HTMLCollection and retrieve the ID of each element. However, your initial approach is incorrect. By using for (key in list), you're iterating over the keys of the HTMLCollection, which are the indices of the elements.
To iterate over the HTMLCollection objects themselves and access their IDs, you can use the following yöntemler:
For modern browsers that support the ES6 for/of syntax, you can use the following code:
var list = document.getElementsByClassName("events"); for (let item of list) { console.log(item.id); }
For browsers that do not support the for/of syntax, you can use the following code:
var list = document.getElementsByClassName("events"); for (var i = 0; i < list.length; i++) { console.log(list[i].id); }
Do not use for/in to iterate over HTMLCollections. It's meant for iterating over object properties, which can lead to unexpected behavior with HTMLCollection objects.
Remember that for modern browsers, the recommended approach is to use the for/of syntax, while for older browsers, the for loop with length property approach will work. Avoid using for/in for HTMLCollections.
The above is the detailed content of How to Correctly Iterate Through HTMLCollection Elements and Retrieve Their IDs?. For more information, please follow other related articles on the PHP Chinese website!