浏览器显示错误: document.getElementsByClassName(...).forEach 不是函数
那是因为getElementsByClassName
不返回数组,它返回一个HTMLCollection https://dom.spec.whatwg.org/#htmlcollection。他们没有forEach
方法(还;可能在某个时候,也可能不会)。
您可以像这样使用数组所具有的:
Array.prototype.forEach.call(document.getElementsByClassName("oneResult"), function(element) {
// Use `element` here
});
或者在现代浏览器(或使用polyfill)上,您可以从集合中创建一个数组:
Array.from(document.getElementsByClassName("oneResult")).forEach(function(element) {
// Use `element` here
});
另一种选择是添加forEach
to HTMLCollection
,你可以在任何模糊现代的浏览器上这样做(甚至是 IE8,如果你用 polyfillArray.prototype.forEach
first):
if (typeof HTMLCollection !== "undefined" && HTMLCollection.prototype && !HTMLCollection.prototype.forEach) {
Object.defineProperty(HTMLCollection.prototype, "forEach", {
value: Array.prototype.forEach,
configurable: true,
writable: true
});
}
最后,请注意,虽然HTMLCollection
没有forEach
, the NodeList
由返回querySelectorAll
确实如此,尽管在某些较旧的浏览器上可能需要进行多填充。看这个答案 https://stackoverflow.com/questions/46929157/foreach-on-queryselectorall-not-working-in-recent-microsoft-browsers/46929259#46929259关于聚填充NodeList
如果需要的话。
More:
-
JavaScript 中的 For-each 数组? https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript(那里的一些答案 - 包括我的 - 有一个关于“类似数组”的东西的部分,其中包括
HTMLCollection
s)
- querySelectorAll、getElementsByClassName 和其他 getElementsBy* 方法返回什么? https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method