html5
主页 > 网页 > html5 >

详解HTML5 HTMLCollection和NodeList的区别

2020-05-01 | 秩名 | 点击:

获取

HTMLCollection 对象

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

注意:

NodeList 对象

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

注意

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>

原文链接:https://www.jb51.net/html5/722925.html
相关文章
最新更新