当前位置: 移动技术网 > IT编程>网页制作>Html5 > HTML5 HTMLCollection和NodeList的区别详解

HTML5 HTMLCollection和NodeList的区别详解

2020年05月09日  | 移动技术网IT编程  | 我要评论

戒酒吧,波澜不惊造句,三亚楼市调控升级

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

获取

htmlcollection 对象

getelementsbytagname() 方法返htmlcollection对象。
htmlcollection 对象类似包含 html 元素的一个数组。

注意:

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

nodelist 对象

大部分浏览器的queryselectorall()返回 nodelist 对象。

注意

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

htmlcollection 与 nodelist 的区别

  1. htmlcollection是 html 元素的集合。(仅包含元素)
  2. nodelist 是一个文档节点的集合。
  3. nodelist 与 htmlcollection 有很多类似的地方。
  4. nodelist 与 htmlcollection 都与数组对象有点类似,可以使用索引 (0, 1, 2, 3, 4, ...) 来获取元素。
  5. nodelist 与 htmlcollection 都有 length 属性。
  6. htmlcollection 元素可以通过 name,id 或索引来获取。
  7. nodelist 只能通过索引来获取。
  8. 只有 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内容请搜索移动技术网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网