• 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、示例

    1. const nodelist = document.querySelectorAll('body')
    2. console.log(nodelist.item(0)) // ...
    3. console.log(nodelist.length) // 1
    4. console.log(nodelist.forEach(item => console.log(item))) // ...
    5. for(var key of nodelist.keys()) {
    6. console.log(nodelist[key]) // ...
    7. }
    8. for(var value of nodelist.values()) {
    9. console.log(value) // ...
    10. }
    11. for(var entry of nodelist.entries()) {
    12. console.log(entry) // [0, body]
    13. }

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

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

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

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

    1. document.getElementsByTagName('body') instanceof HTMLCollection // true
    2. const htmlCollection = document.getElementsByTagName('body')
    3. console.log(htmlCollection.item(0)) // ...
    4. 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() 等。除非你把他转为一个数组,你使用上面所介绍的方法将其转换为数组。

  • 相关阅读:
    scala之偏函数学习
    Linux:多线程中的互斥与同步
    运维:k8s常用命令大全
    Lock锁以及解决生产者消费者的方案
    电池集成充电解决方案提供商【XCharge Group】获得壳牌风险投资
    前端实现复制功能
    开展自动化方案时,需要考虑哪些内容,开展实施前需要做哪些准备呢?
    转发能力、线速转发、交换带宽
    Python 面试复习题整理
    12.从架构设计角度分析AAC源码-Room源码解析第1篇:当前demo为主线查看涉及的Room源码解析
  • 原文地址:https://blog.csdn.net/m0_37911706/article/details/127118261