JavaScript Interview Question #54

What is the difference between an HTMLCollection and a NodeList?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

Both represent collections of DOM nodes, but they are produced by different DOM APIs and can have different behavior. Many HTMLCollection objects are live, meaning they reflect relevant DOM changes automatically. A NodeList may be live or static depending on the API; querySelectorAll returns a static NodeList.

Detailed Explanation

Both represent collections of DOM nodes, but they are produced by different DOM APIs and can have different behavior. Many HTMLCollection objects are live, meaning they reflect relevant DOM changes automatically. A NodeList may be live or static depending on the API; querySelectorAll returns a static NodeList.

They are array-like but are not ordinary Arrays. Convert them with Array.from or spread syntax when normal array methods are required.

Code Example

const liveItems =
    document.getElementsByClassName("item");

const staticItems =
    document.querySelectorAll(".item");

const array = Array.from(staticItems);
const names = array.map(x => x.textContent);