Skip to main content

Command Palette

Search for a command to run...

HTML Collection vs Nodelist

Published
1 min read
HTML Collection vs Nodelist
N

Aspiring Frontend Engineer

Both are array-like objects but they differ in some areas

HTML Collection
  • is a collection of element nodes
  • is returned by 'getElementsByClassName' and 'getElementsByTagName'

Nodelist

  • contains all types of nodes: element nodes, text nodes, etc
  • is returned by 'querySelectorAll'

====

NodeList returned by querySelectorAll is static. Static means that it doesnt get updated if more items that match the query are added, removed, modified. It doesnt mean that updating properties of an item inside a nodelist wont be reflected.

<html>
  <p class="luck">easy mate</p>
  <p class="luck">easy bait</p>
  <p class="luck">easy late</p>
</html>
const pEls = document.querySelectorAll("p");
console.log(pEls); // {p, p , p}
document.querySelector("html").appendChild(document.createElement("p"));
console.log(pEls); // {p, p , p}

so it didnt get added to the node list but if we did the same but used getElementsByTagName it would get reflected and we would see the fourth p added to the html collection