设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 手机 数据
当前位置: 首页 > 站长学院 > MySql教程 > 正文

HTML5 HTMLCollection和NodeList的区别详解

发布时间:2020-05-10 12:18 所属栏目:115 来源:站长网
导读:getElementsByTagName() 方法返HTMLCollection对象。 HTMLCollection 对象类似包含 HTML 元素的一个数组。 注意: HTMLCollection 不是一个数组! HTMLCollection 看起来可能是一个数组,但其实不是。 你可以像数组一样,使用索引来获取元素。 HTMLCollect

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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!

(编辑:ASP站长网)

    网友评论
    推荐文章
      热点阅读