TExcelTAD
Home › XML › DOM Node List

XML DOM Node List

Methods that return several nodes give you a list-like collection, not a real JavaScript array. Understanding the three collection types — NodeList, HTMLCollection and NamedNodeMap — and the difference between live and static lists will save you from some confusing bugs.

Collection types

Returned by Type Live?
childNodes NodeList Live
querySelectorAll() NodeList Static
getElementsByTagName(), children HTMLCollection (yes, even in XML) Live
attributes NamedNodeMap Live

All of them have a length and can be indexed with [i] or .item(i). All can be looped with for…of and converted to a real array with [...list] or Array.from(list).

Looping over a list

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<library>
      <book genre="fantasy"><title>The Hobbit</title><price>8.99</price></book>
      <book genre="science"><title>A Brief History of Time</title><price>12.50</price></book>
      <book genre="fantasy"><title>Cien años de soledad</title><price>10.00</price></book>
    </library>`;
    const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
    const titles = xmlDoc.getElementsByTagName('title');

    // 1. Classic index loop
    for (let i = 0; i < titles.length; i++) console.log(i, titles[i].textContent);

    // 2. for...of
    for (const t of titles) console.log('-', t.textContent);

    // 3. Convert to an array to use map/filter/reduce
    const prices = Array.from(xmlDoc.getElementsByTagName('price'), p => Number(p.textContent));
    console.log('Total price:', prices.reduce((a, b) => a + b, 0).toFixed(2));
  </script>
</body>
</html>

Note: NodeList has forEach, but HTMLCollection does not. Convert with [...list] first if you want forEach, map or filter.

Live vs static

A live list is a window onto the document: when the document changes, the list changes too. A static list is a snapshot taken when you called the method.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString(
      '<library><book>A</book><book>B</book></library>', 'application/xml');

    const live = xmlDoc.getElementsByTagName('book');
    const snapshot = xmlDoc.querySelectorAll('book');
    console.log('before:', live.length, snapshot.length);

    const extra = xmlDoc.createElement('book');
    extra.textContent = 'C';
    xmlDoc.documentElement.appendChild(extra);

    console.log('after :', live.length, snapshot.length);
  </script>
</body>
</html>

The classic live-list bug

Removing items while looping forwards over a live list skips every other item, because the list shrinks under your feet:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const make = () => new DOMParser().parseFromString(
      '<list><item>1</item><item>2</item><item>3</item><item>4</item></list>', 'application/xml');

    // Buggy: live list + forward loop
    let doc = make();
    let items = doc.getElementsByTagName('item');
    for (let i = 0; i < items.length; i++) items[i].remove();
    console.log('buggy left:', doc.documentElement.textContent);

    // Fix 1: loop over a static copy
    doc = make();
    for (const it of [...doc.getElementsByTagName('item')]) it.remove();
    console.log('fix 1 left:', JSON.stringify(doc.documentElement.textContent));

    // Fix 2: loop backwards
    doc = make();
    items = doc.getElementsByTagName('item');
    for (let i = items.length - 1; i >= 0; i--) items[i].remove();
    console.log('fix 2 left:', JSON.stringify(doc.documentElement.textContent));
  </script>
</body>
</html>

The attribute list: NamedNodeMap

element.attributes is a collection of attribute nodes, accessible by index or by name:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString(
      '<book id="b1" genre="fantasy" lang="en" pages="310"/>', 'application/xml');
    const attrs = xmlDoc.documentElement.attributes;

    console.log('count:', attrs.length);
    for (const a of attrs) console.log(`  ${a.name} = ${a.value}`);
    console.log('by name:', attrs.getNamedItem('pages').value);
    console.log('by index:', attrs[1].name);
  </script>
</body>
</html>

Tip: The order of attributes in a NamedNodeMap is not guaranteed by the XML standard. Look attributes up by name, not by position.

Test yourself

Which method returns a **static** list?

  1. getElementsByTagName()
  2. childNodes
  3. querySelectorAll()
  4. children

Why can removing elements in a forward loop over a live list skip items?

  1. Live lists are read-only
  2. The list shrinks after each removal, so the next item moves into the current index
  3. Removed items are re-added
  4. Live lists are sorted alphabetically

How do you use map() on the result of getElementsByTagName()?

  1. Call .map() directly
  2. Convert it first, e.g. [...list].map(...) or Array.from(list, fn)
  3. It's impossible
  4. Use .forEachMap()