HTML5標簽HTMLCollection和NodeList的區別詳解

2020-05-21 16:56:45 來源:互聯網作者:佚名 人氣: 次閱讀 85 條評論

文章主要介紹了HTML5中的HTMLCollection和NodeList的區別詳解,文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學習學習吧HTML5 HTMLCollection和NodeList的...

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

您可能感興趣的文章

相關文章