js中getElementsByClassName返回的是什么

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

阅读 10.2k
3 个回答

如依云大大所说,是 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+才支持。
感觉发现了新大陆,感谢题主提供问题~

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

请输入图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题