Go Back

HTML Collection vs Nodelist

Updated on 20 September, 2019

HTML5

  • Both are collection of DOM nodes
  • Nodelist can contain any type of nodes like text,comment,element nodes but HTML collection contains element nodes only

All items in the DOM are referred to as nodes. There are many types of nodes. Main ones are element nodes, Text nodes and Comment nodes. An HTML element is referred to as an element node, text outside an element is text node and comments are refered to as comment nodes

You can see examples for different types of nodes we discussed in the below html

<!DOCTYPE html>
<html>

  <head>
    <title>Different type of nodes</title>
  </head>

  <body>
    <p>An element node</p>
    <!-- a comment node -->
    This is a text node.
  </body>

</html>

There are other differences also

We can inspect that using an example HTML and Javascript

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Nodelist vs HTMLCollection</title>
</head>
<body>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quo, doloribus.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus amet quibusdam officia ullam doloremque facere tempore ut, dolor excepturi eum.</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Saepe dolorum quis quia distinctio debitis ipsum aliquid excepturi consequatur odit sit hic rerum provident dolorem ea ratione, vel iusto quam dignissimos.</p>

<script>

const nodeList = document.querySelectorAll('p');
console.log(nodeList);
nodeList.forEach((el)=> console.log(el))

const htmlCollection = document.getElementsByTagName('p');
console.log(htmlCollection)
// htmlCollection.forEach((el)=>console.log(el))
Array.from(htmlCollection).forEach((el)=>console.log(el))
</script>
</body>
</html>
  • In the Javascript above we are using querySelectorAll which returns a nodelist. We can iterate over a nodelist using forEach.

    //This works
    nodeList.forEach((el)=> console.log(el))
    

But getElementsByTagName returns an HTMLCollection. We cannot iterate over it using forEach.

//This returns an error
htmlCollection.forEach((el)=>console.log(el))

That HTMLCollection can be converted to an array using Array.from() and iterated.

Array.from(htmlCollection).forEach((el)=>console.log(el))

ES6 spread operator also can be used to convert an HTMLCollection to an array. We may need babel as a transpiler to compile ES6 code. See it in the codepen below

Check your console you can see the looped output from the codepen script.

  • HTMLCollection is dynamic but nodelists are typically static. HTMLCollection updates itself when there are changes to DOM.

  • Neither HTMLCollection nor NodeList support the array prototype methods like push,pop or splice.

Thank you for reading.

Go Back