版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GreyBearChao/article/details/82854179
- 这三个都是类数组对象。
- HTMLCollection只包含元素节点,而NodeList包含任何节点类型。
- HTMLCollection对象可以调用item()和namedItem()方法,NodeList对象只能调用item()方法。在获取元素时,两者都可以通过方括号的语法或item()方法。HTMLCollection对象允许通过namedItem()方法,传入一个name或id获取元素。
- 一些旧版本浏览器中的方法(如:getElementsByClassName())返回的是 NodeList 对象,而不是 HTMLCollection 对象。所有浏览器的 childNodes 属性返回的是 NodeList 对象。大部分浏览器的 querySelectorAll() 返回 NodeList 对象。getElementsByTagName()返回HTMLCollection对象。
- NamedNodeMap对象是通过node.attributes属性获取,获取到由该元素的所有属性构成的伪数组对象。
例:
<body>
<div>
<a href="#" id="a1">1</a>
<a href="a.html" name="a2">2</a>
</div>
</body>
<script>
// 获取一个HTMLCollection对象
var res = document.getElementsByTagName("a");
console.log(res);
console.log(res.item(0))
console.log(res[0])
console.log(res.namedItem('a1'))
console.log(res.namedItem('a2'))
// 结果如下图所示:
</script>