面试题:HTMLCollection和NodeList区别

37 阅读1分钟

Node和Element

  • DOM是一棵树,所有节点都是Node
  • Node是Element的基类
  • Element是其他HTML元素的基类,如HTMLDivElement

image.png

代码演示

  • 关系:

image.png

HTMLCollection和NodeList

  • HTMLCollection是Element的集合
  • NodeList是Node集合

HTMLCollection

<body>
  <p id="p1">
    <b>node</b>vs <em>element</em><!--注释-->
  </p>
  <script>
    const p1 = document.getElementById('p1')
    console.log(p1.children) // children 是当前元素的子元素 只包含element的子元素 不包含text和comment
    console.log(p1.children instanceof HTMLCollection); // true
    console.log(p1.children instanceof NodeList); //false
  </script>

image.png

NodeList

  <p id="p1">
    <b>node</b>vs <em>element</em><!--注释-->
  </p>
  <script>
    const p1 = document.getElementById('p1')
    console.log(p1.childNodes)
    console.log(p1.childNodes instanceof NodeList) // true
    console.log(p1.childNodes instanceof HTMLCollection) // false
  </script>

image.png

补充

    console.log(p1.tagName); // element
    console.log(p1.nodeName); // node 
    console.log(p1.nodeType); // node 

划重点

  • 获取Node和Element的返回结果可能不一样
  • 如elem.childNodes和elem.children不一样
  • 前者会包含Text和Comment节点,后者不会

扩展:类数组 -> 数组

  • HTMLCollection 和 NodeList 都不是数组,而是类数组
const arr1 = Array.from(list)
const arr2 = Array.prototype.slice.call(list)
const arr3 = [...list]