好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

HTML5 HTMLCollection和NodeList的区别详解

本文主要介绍了HT ML 5 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 元素可以通过 n am e,id 或索引来获取。 NodeList 只能通过索引来获取。 只有 NodeList 对象有包含属性节点和文本节点。

代码

<!DOCTY PE  html>
<html lang="en">
<head>
    < ;m eta charset="UTF-8">
    <meta name="viewport" content="width=device-width, in IT ial -s cale=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) //un define  

    </script>
</body>
</html>

到此这篇关于HTML5 HTMLCollection和NodeList的区别详解的 文章 就介绍到这了,更多相关HTML5 HTMLCollection NodeList内容请搜索以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!

总结

以上是 为你收集整理的 HTML5 HTMLCollection和NodeList的区别详解 全部内容,希望文章能够帮你解决 HTML5 HTMLCollection和NodeList的区别详解 所遇到的问题。

如果觉得 网站内容还不错, 推荐好友。

查看更多关于HTML5 HTMLCollection和NodeList的区别详解的详细内容...

  阅读:18次