HTML5 HTMLCollection和NodeList的区别详解
getElementsByTagName() 方法返HTMLCollection对象。 注意: 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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家! (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |