NodeList和HTMLCollection的区别

一、NodeList:文档节点的集合,只能通过索引获取

     1、获取NodeList对象的方法:

       (1)一些旧版本浏览器中的方法(如 getElementsByClassName()),返回的是 NodeList 对象,而不是 HTMLCollection 对象。

      (2)所有浏览器的 Node.childNodes 属性返回的是 NodeList 对象。

      (3)大部分浏览器的 document.querySelectorAll() 返回 NodeList 对象。

    2、NodeList 对象中的属性和方法:

     (1)item() —— 返回某个元素基于文档树的索引

     (2)length —— 返回 NodeList 的节点数量。

     (3)NodeList.forEach() 方法用于遍历 NodeList 的所有成员。它接受一个回调函数作为参数,每一轮遍历就执行一次这个回调函数,用法与数组实例的 forEach 方法完全一致。

     (4)NodeList.keys()/values()/entries() —— 这三个方法都返回一个 ES6 的遍历器对象,可以通过 for...of 循环遍历获取每一个成员的信息。

 区别keys() 返回键名的遍历器,values() 返回键值的遍历器,entries() 返回的遍历器同时包含键名和键值的信息。

   3、示例

const nodelist = document.querySelectorAll('body')
 
console.log(nodelist.item(0)) // <body>...</body>
console.log(nodelist.length) // 1
console.log(nodelist.forEach(item => console.log(item))) // <body>...</body>
 
for(var key of nodelist.keys()) {
  console.log(nodelist[key]) // <body>...</body>
}
 
for(var value of nodelist.values()) {
  console.log(value) // <body>...</body>
}
 
for(var entry of nodelist.entries()) {
  console.log(entry) // [0, body]
}

二、HTMLCollection:html元素的集合,可以通过id、name或索引获取

     1、HTMLCollection 对象中的属性和方法:

       (1)item(index) —— 返回 HTMLCollection 中指定索引的元素,不存在返回 null。

       (2)length(只读)—— 返回 HTMLCollection 中元素的数量。

document.getElementsByTagName('body') instanceof HTMLCollection // true
 
const htmlCollection = document.getElementsByTagName('body')
console.log(htmlCollection.item(0)) // <body>...</body>
console.log(htmlCollection.length()) // 1

三、HTMLCollection 与 NodeList 的区别

       1、NodeList 是一个静态集合,其不受 DOM 树元素变化的影响;相当于是 DOM 树快照,节点数量和类型的快照,就是对节点增删,NodeList 感觉不到。但是对节点内部内容修改,是可以感觉到的,比如修改 innerHTML。

       2、HTMLCollection 是动态绑定的,是一个的动态集合, DOM 树发生变化,HTMLCollection 也会随之变化,节点的增删是敏感的。只有 NodeList 对象有包含属性节点和文本节点。

       3、HTMLCollection 元素可以通过 name,id 或 index 索引来获取。NodeList 只能通过 index 索引来获取。

       4、HTMLCollection 和 NodeList 本身无法使用数组的方法:pop(),push(),或 join() 等。除非你把他转为一个数组,你使用上面所介绍的方法将其转换为数组。

猜你喜欢

转载自blog.csdn.net/m0_37911706/article/details/127118261
今日推荐