首页 > js中getElementsByClassName返回的是什么

js中getElementsByClassName返回的是什么

我试了一下Array.isArray()为false,也不是NodeList,那返回的是个什么东西呢?如何准确检测它的类型呢


>>> document.getElementsByClassName('a')
HTMLCollection[]

是一种 array-like 对象,在 JavaScript 有 Array 之前就已经存在的东西。参见:Why are there so many array-like objects in the DOM?。


不是NodeList,是HTMLCollection。和NodeList差不多,都是类数组的对象。使用instanceof HTMLCollection返回true。


如依云大大所说,是 HTMLCollection.

在我往下贴回答之前,我想说getElmentsByClassName,亲,少了个字母哦。//难怪我刚才在console运行报错。

MDN对getElementsByClassName的解释>>

var elements = document.getElementsByClassName(names); // or:
var elements = rootElement.getElementsByClassName(names);
elements is a HTMLCollection of found elements.//看这里。

为什么不是NodeList,我猜题主应该是看过getElementsByTagName
关于TagName,这里又有一篇解释>>

Note: While the W3C DOM 3 Core specification says elements is a NodeList that was simply because of a an attempt to have the "core" specification not depend on the "html" specification at that time. The DOM 4 draft says that elements is an HTMLCollection.

所以我试了下两个方法比较类型。

我的chrome版本两个方法返回的对象都不是NodeList类型了。

PS:之前在看这个方法的时候,发现ie那边只有ie9+才支持。
感觉发现了新大陆,感谢题主提供问题~

【热门文章】
【热门文章】