thesublimeobject
thesublimeobject

Reputation: 1403

Iterating an HTMLCollection object using for-of loop

I'm using babel-polyfill and I'm trying to iterate an HTMLCollection object using for-of loop:

const elements = document.getElementsByClassName('some-class')
for (const element of elements) {
  console.log(element)
}

It's not working. I'm getting an error elements[Symbol.iterator] is not a function. How to make it work correctly?

Upvotes: 3

Views: 2556

Answers (1)

Michał Perłakowski
Michał Perłakowski

Reputation: 92531

From "Iterable DOM collections" on the core-js GitHub page:

Some DOM collections should have iterable interface or should be inherited from Array. That mean they should have keys, values, entries and @@iterator methods for iteration. So add them. Module web.dom.iterable:

{
  NodeList,
  DOMTokenList,
  MediaList,
  StyleSheetList,
  CSSRuleList
}
  #values()     -> iterator
  #keys()       -> iterator
  #entries()    -> iterator
  #@@iterator() -> iterator (values)

As you can see, that list doesn't include HTMLCollection. In order to be able to use for-of loop with HTMLCollection, you have to manually assign Array.prototype.values to HTMLCollection.prototype[Symbol.iterator]. See this example:

HTMLCollection.prototype[Symbol.iterator] = Array.prototype.values

for (const element of document.getElementsByTagName('a')) {
  console.log(element.href)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.min.js"></script>
<a href="//www.google.com">Google</a>
<a href="//www.github.com">GitHub</a>

Alternatively, you can just use document.querySelectorAll(), which a returns a NodeList object.

Upvotes: 4

Related Questions