我使用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
。如何让它正常工作?
答案 0 :(得分:4)
来自"Iterable DOM collections" on the core-js GitHub page:
某些DOM集合应该具有iterable interface或应该是inherited from
Array
web.dom.iterable
。那意味着 他们应该有keys
,values
,entries
和@@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;
或者,您可以使用this,它会返回NodeList
个对象。