HTML5 HTMLCollection和NodeList的区别详解_html5_网页制作

这篇文章主要介绍了HTML5 HTMLCollection和NodeList的区别详解,文中通过示例

HTML5 HTMLCollection和NodeList的区别详解_html5_网页制作

这篇文章主要介绍了HTML5 HTMLCollection和NodeList的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

本文主要介绍了HTML5 HTMLCollection和NodeList的区别详解,分享给大家,具体如下:

获取

HTMLCollection 对象

getElementsByTagName() 方法返HTMLCollection对象。
HTMLCollection 对象类似包含 HTML 元素的一个数组。

注意:

HTMLCollection 不是一个数组!
HTMLCollection 看起来可能是一个数组,但其实不是。
你可以像数组一样,使用索引来获取元素。
HTMLCollection 无法使用数组的方法: valueOf(), pop(), push(), 或 join()。

NodeList 对象

大部分浏览器的querySelectorAll()返回 NodeList 对象。

注意

节点列表不是一个数组!
节点列表看起来可能是一个数组,但其实不是。
你可以像数组一样,使用索引来获取元素。
节点列表无法使用数组的方法: valueOf(), pop(), push(), 或 join() 。

HTMLCollection 与 NodeList 的区别

HTMLCollection是 HTML 元素的集合。(仅包含元素)
NodeList 是一个文档节点的集合。
NodeList 与 HTMLCollection 有很多类似的地方。
NodeList 与 HTMLCollection 都与数组对象有点类似,可以使用索引 (0, 1, 2, 3, 4, …) 来获取元素。
NodeList 与 HTMLCollection 都有 length 属性。
HTMLCollection 元素可以通过 name,id 或索引来获取。
NodeList 只能通过索引来获取。
只有 NodeList 对象有包含属性节点和文本节点。

代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<P>1</P>
<P id="p2">2</P>
<P>3</P>
<P>4</P>
<P>5</P>
<script>
// getElementsByTagName() 方法返回 HTMLCollection 对象。
const myCollection = document.getElementsByTagName(\’p\’);
console.log(myCollection)
// 大部分浏览器的 querySelectorAll() 返回 NodeList 对象。
const myNodeList = document.querySelectorAll("p");
console.log(myNodeList)
console.log(myNodeList ===myCollection) //false
console.log(myCollection.p2) // <P id="p2">2</P>
console.log(myNodeList.p2) //undefine

</script>
</body>
</html>

到此这篇关于HTML5 HTMLCollection和NodeList的区别详解的文章就介绍到这了,更多相关HTML5 HTMLCollection NodeList内容请搜索3399IT网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持3399IT网!

本文为网络共享文章,如有侵权请联系邮箱485837881@qq.com

作者: tiger

为您推荐

返回顶部