HTML5標籤HTMLCollection和NodeList的區別詳解

佚名發表於2020-05-21

文章主要介紹了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內容請搜尋以前的文章或繼續瀏覽下面的相關文章

相關文章