Dom Node List in XML
DOM NodeList in XML
A NodeList is a collection (like an array) of nodes returned by DOM methods such as:
getElementsByTagName()childNodesquerySelectorAll()(in HTML DOM)
What is a NodeList?
It is array-like, meaning you can access items by index:
nodeList[0].It is live or static depending on the method (e.g.,
getElementsByTagNamereturns a live NodeList, reflecting changes in the DOM).You can loop over a NodeList using
forloop orfor...of(in modern browsers).
Example XML
<library> <book id="101"><title>Effective Java</title></book> <book id="102"><title>Clean Code</title></book> <book id="103"><title>JavaScript: The Good Parts</title></book></library>Getting a NodeList in JavaScript
// Assuming xmlDoc is the parsed XML documentconst books = xmlDoc.getElementsByTagName("book"); // NodeList of all <book> elementsconsole.log(books.length); // Number of <book> nodes// Access individual nodesconst firstBook = books[0];console.log(firstBook.getAttribute("id")); // "101"Looping Through a NodeList
for (let i = 0; i < books.length; i++) { const book = books[i]; const title = book.getElementsByTagName("title")[0].textContent; console.log(`Book ID: ${book.getAttribute("id")}, Title: ${title}`);}Or using modern syntax:
for (const book of books) { const title = book.getElementsByTagName("title")[0].textContent; console.log(`Book ID: ${book.getAttribute("id")}, Title: ${title}`);}Important Notes
NodeList is not exactly an Array, so array methods like
.map(),.filter()won’t work unless you convert it:
const booksArray = Array.from(books);booksArray.forEach(book => { console.log(book.getAttribute("id"));});In older browsers, you may need
forloops instead offor...of.
Summary
| Method | Returns | Description |
|---|---|---|
getElementsByTagName() | NodeList (live) | All elements with given tag name |
childNodes | NodeList (live) | All child nodes (elements, text, comments) |
querySelectorAll() | NodeList (static) | All elements matching selector |
If you want, I can provide a runnable HTML + JS example demonstrating NodeList usage on XML!