DOM Nodelist
JavaScript HTML DOM NodeList
Section titled “JavaScript HTML DOM NodeList”A NodeList is a collection of document nodes (e.g., elements, text nodes). It is often returned by DOM manipulation methods.
HTML DOM NodeList
Section titled “HTML DOM NodeList”Methods like document.querySelectorAll() and element.childNodes return a NodeList. Older methods like document.getElementsByTagName() also return a NodeList (or an HTMLCollection, which is similar).
A NodeList is an array-like collection, meaning it has a length property and its items can be accessed by index (e.g., nodeList[0]), but it’s not a true JavaScript Array. Therefore, some array methods might not be directly available.
The following code selects all <p> elements in a document using querySelectorAll:
const paragraphs = document.querySelectorAll("p");Note: The index for accessing items in a NodeList starts at 0.
NodeList Length
Section titled “NodeList Length”The length property of a NodeList indicates the number of nodes in the list:
const myNodeList = document.querySelectorAll("article > p"); // Selects all <p> children of <article>document.getElementById("demo").textContent = `Found ${myNodeList.length} paragraphs.`;The length property is useful for iterating through the nodes in a NodeList.
Modern Iteration Methods:
Section titled “Modern Iteration Methods:”You can iterate over a NodeList using a for...of loop or the forEach method (which is available directly on NodeLists in modern browsers):
// Using for...of loopconst articles = document.querySelectorAll('article');for (const article of articles) { article.style.border = '1px solid blue';}
// Using forEach methodconst listItems = document.querySelectorAll('ul > li');listItems.forEach((item, index) => { item.textContent = `Item ${index + 1}`;});Converting NodeList to an Array
Section titled “Converting NodeList to an Array”While NodeLists are array-like, they don’t have all array methods like map(), filter(), etc. If you need to use these methods, you can convert the NodeList to a true array using Array.from() or the spread syntax (...):
const allDivsNodeList = document.querySelectorAll('div');
// Using Array.from()const allDivsArray1 = Array.from(allDivsNodeList);const divHeights = allDivsArray1.map(div => div.offsetHeight);
// Using spread syntaxconst allDivsArray2 = [...allDivsNodeList];const divsWithClass = allDivsArray2.filter(div => div.classList.contains('special'));Key takeaway: A NodeList is a collection of nodes, similar to an array, but not identical. Modern JavaScript provides convenient ways to iterate over NodeLists (like forEach and for...of) and to convert them into true arrays when needed using Array.from() or the spread syntax. |
|---|