(编辑:jimmy 日期: 2025/11/4 浏览:2)
本文主要介绍了HTML5 HTMLCollection和NodeList的区别详解,分享给大家,具体如下:
获取
HTMLCollection 对象
getElementsByTagName() 方法返HTMLCollection对象。
HTMLCollection 对象类似包含 HTML 元素的一个数组。
注意:
NodeList 对象
大部分浏览器的querySelectorAll()返回 NodeList 对象。
注意
HTMLCollection 与 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>