Why is objects.forEach not a function let objects =…
- User
Why is objects.forEach not a function let objects = document.getElementsByTagName("img"); objects.forEach(item => {console.log(item)});
- Assistant
The
document.getElementsByTagNamemethod returns anHTMLCollection, which is array-like but does not include theArray.prototypemethods such asforEach. In JavaScript, the term "array-like" is used to refer to data structures that resemble arrays in that they have indexed elements and alengthproperty, but they do not necessarily have all the array methods (likeforEach,map,filter, etc.).If you want to use
forEachon the elements returned bydocument.getElementsByTagName, you can convert theHTMLCollectioninto a proper array usingArray.fromor the spread operator (...). Here are two ways you can achieve this:Using
Array.from:let objects = document.getElementsByTagName("img"); Array.from(objects).forEach(item => { console.log(item); });Using the spread operator: