XML DOM NodeList

When DOM methods like getElementsByTagName() return multiple nodes, they return a NodeList — a collection of nodes. Understanding how to work with NodeLists is essential for processing XML with multiple repeating elements.

NodeList Basics

var books = xmlDoc.getElementsByTagName("book");

// Length — number of nodes in the list
console.log(books.length);     // e.g., 3

// Access by index (0-based)
var first = books[0];
var second = books[1];
var last = books[books.length - 1];

// Using item() method — same as bracket notation
var first2 = books.item(0);

Looping Over a NodeList

var products = xmlDoc.getElementsByTagName("product");

// Traditional for loop — most compatible
for (var i = 0; i < products.length; i++) {
  console.log(products[i].getAttribute("id"));
}

// Modern Array.from (converts NodeList to a true Array)
Array.from(products).forEach(function(product) {
  console.log(product.textContent);
});

Live vs Static NodeLists

NodeLists returned by getElementsByTagName() are live — they update automatically when the document changes. If you add a book element, the books NodeList immediately contains the new node. NodeLists returned by querySelectorAll() are static — they do not update after creation.

// Live NodeList
var books = xmlDoc.getElementsByTagName("book");
console.log(books.length);     // 2

// Add a new book
var newBook = xmlDoc.createElement("book");
xmlDoc.documentElement.appendChild(newBook);

console.log(books.length);     // 3 — automatically updated!

Converting NodeList to Array

// Method 1: Array.from
var booksArray = Array.from(xmlDoc.getElementsByTagName("book"));

// Method 2: spread operator
var booksArray2 = [...xmlDoc.getElementsByTagName("book")];

// Now you can use array methods
var titles = booksArray.map(book =>
  book.getElementsByTagName("title")[0].textContent
);

Key Points to Remember

  • A NodeList is a collection of nodes — not a JavaScript array, but array-like.
  • Access nodes by index (books[0]) or using the item() method (books.item(0)).
  • NodeLists from getElementsByTagName() are live — they reflect document changes automatically.
  • Use Array.from() or the spread operator [...] to convert a NodeList to a true array.
  • Always check .length before accessing nodes to avoid null reference errors.

Leave a Comment

Your email address will not be published. Required fields are marked *