• 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() 等。除非你把他转为一个数组,你使用上面所介绍的方法将其转换为数组。

  • 相关阅读:
    合并文件解决HiveServer2内存溢出方案
    MPI学习笔记(二):矩阵相乘的两种实现方法
    终于解决VScode中python/C++打印中文全是乱码的问题了
    山东省首版次高端软件申报指导
    python socket编程2 - socket创建发送方所需参数的获得
    本地MQTT服务器搭建(EMQX)
    混凝土板材及砌块生产线数字孪生可视化管理系统,实现智慧工厂车间智能化数字化管理
    Security思想项目总结
    技术分享| anyRTC服务4.3升级
    2023鸿蒙预定未来,环境搭建学习
  • 原文地址:https://blog.csdn.net/m0_37911706/article/details/127118261