HTML Elements vs NodeList
Understanding the difference between HTML Elements and NodeList is crucial for effective DOM manipulation.
Key concepts
HTML Elements
Represent DOM elements as objects with specific properties like id, className, and innerHTML. Accessed using methods like getElementById or getElementsByClassName.
Exampleconst header = document.getElementById('title'); // HTMLElement
console.log(header.id); // "title"NodeList
A collection of DOM nodes, which can be elements, text, or comments. Returned by methods like querySelectorAll. Similar to arrays but lacks many array methods.
Exampleconst nodeList = document.querySelectorAll('p'); // NodeList
console.log(nodeList.length); // Number of <p> elementsExamples
Converting NodeList to Array:
const paragraphs = Array.from(document.querySelectorAll('p'));
paragraphs.forEach((p) => console.log(p.textContent));Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus