thesublimeobject thesublimeobject - 1 year ago 189
Javascript Question

Iterating an HTMLCollection object using for-of loop

I'm using babel-polyfill and I'm trying to iterate an

object using for-of loop:

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

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

Answer Source

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:

  #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')) {
<script src=""></script>
<a href="//">Google</a>
<a href="//">GitHub</a>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download