使用for-of循环迭代HTMLCollection对象

时间:2016-09-29 22:09:10

标签: javascript dom ecmascript-6 htmlcollection babel-polyfill

我使用babel-polyfill并尝试使用for-of循环迭代HTMLCollection对象:

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

它无法正常工作。我收到错误elements[Symbol.iterator] is not a function。如何让它正常工作?

1 个答案:

答案 0 :(得分:4)

来自"Iterable DOM collections" on the core-js GitHub page

  

某些DOM集合应该具有iterable interface或应该是inherited from Array   web.dom.iterable。那意味着   他们应该有keysvaluesentries@@iterator方法   用于迭代。所以添加它们。模   document.querySelectorAll()

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

如您所见,该列表不包含HTMLCollection。为了能够使用HTMLCollection的for-of循环,您必须手动将Array.prototype.values分配给HTMLCollection.prototype[Symbol.iterator]。见这个例子:



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>
&#13;
&#13;
&#13;

或者,您可以使用this,它会返回NodeList个对象。