HTMLCollection和NodeList的區別

獲取

HTMLCollection 對象

getElementsByTagName() 方法返HTMLCollection對象。
HTMLCollection 對象相似包含 HTML 元素的一個數組。
注意: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>
相關文章
相關標籤/搜索