佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > HTML5 HTMLCollection和NodeList的區(qū)別詳解

HTML5 HTMLCollection和NodeList的區(qū)別詳解

熱門標(biāo)簽:阿里云 硅谷的囚徒呼叫中心 美圖手機(jī) 百度競價點擊價格的計算公式 網(wǎng)站建設(shè) 檢查注冊表項 智能手機(jī) 使用U盤裝系統(tǒng)

本文主要介紹了HTML5 HTMLCollection和NodeList的區(qū)別詳解,分享給大家,具體如下:

獲取

HTMLCollection 對象

getElementsByTagName() 方法返HTMLCollection對象。
HTMLCollection 對象類似包含 HTML 元素的一個數(shù)組。

注意:

  • HTMLCollection 不是一個數(shù)組!
  • HTMLCollection 看起來可能是一個數(shù)組,但其實不是。
  • 你可以像數(shù)組一樣,使用索引來獲取元素。
  • HTMLCollection 無法使用數(shù)組的方法: valueOf(), pop(), push(), 或 join()。

NodeList 對象

大部分瀏覽器的querySelectorAll()返回 NodeList 對象。

注意

  • 節(jié)點列表不是一個數(shù)組!
  • 節(jié)點列表看起來可能是一個數(shù)組,但其實不是。
  • 你可以像數(shù)組一樣,使用索引來獲取元素。
  • 節(jié)點列表無法使用數(shù)組的方法: valueOf(), pop(), push(), 或 join() 。

HTMLCollection 與 NodeList 的區(qū)別

  1. HTMLCollection是 HTML 元素的集合。(僅包含元素)
  2. NodeList 是一個文檔節(jié)點的集合。
  3. NodeList 與 HTMLCollection 有很多類似的地方。
  4. NodeList 與 HTMLCollection 都與數(shù)組對象有點類似,可以使用索引 (0, 1, 2, 3, 4, ...) 來獲取元素。
  5. NodeList 與 HTMLCollection 都有 length 屬性。
  6. HTMLCollection 元素可以通過 name,id 或索引來獲取。
  7. NodeList 只能通過索引來獲取。
  8. 只有 NodeList 對象有包含屬性節(jié)點和文本節(jié)點。

代碼

<!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>

到此這篇關(guān)于HTML5 HTMLCollection和NodeList的區(qū)別詳解的文章就介紹到這了,更多相關(guān)HTML5 HTMLCollection NodeList內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!

標(biāo)簽:賀州 懷化 煙臺 湖北 湘潭 黃山 山南 通遼

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《HTML5 HTMLCollection和NodeList的區(qū)別詳解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    永兴县| 岗巴县| 淮南市| 郴州市| 岚皋县| 游戏| 修文县| 石楼县| 那曲县| 库车县| 湘潭县| 于田县| 塘沽区| 诸暨市| 武胜县| 西畴县| 苍溪县| 浑源县| 玛纳斯县| 玉龙| 葫芦岛市| 娄烦县| 水富县| 西充县| 砀山县| 洮南市| 闽侯县| 东丽区| 松溪县| 健康| 汕头市| 琼结县| 宝鸡市| 高唐县| 长宁县| 泸水县| 克什克腾旗| 中山市| 阳曲县| 新郑市| 翼城县|