XML DOM Accessing Nodes
Before you can read or change a node, you need to get hold of it. The DOM offers three main routes:
- By name —
getElementsByTagName(). - By selector —
querySelector()/querySelectorAll()(CSS selectors) or XPath. - By relationship — walking from a known node via
parentNode,childNodes, siblings and so on.
getElementsByTagName()
Returns all descendant elements with the given name, in document order. You can call it on the document (search everywhere) or on an element (search only inside it).
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<library>
<book id="b1" genre="fantasy"><title>The Hobbit</title><author>J. R. R. Tolkien</author><year>1937</year></book>
<book id="b2" genre="science"><title>A Brief History of Time</title><author>Stephen Hawking</author><year>1988</year></book>
<book id="b3" genre="fantasy"><title>Cien años de soledad</title><author>Gabriel García Márquez</author><year>1967</year></book>
</library>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const titles = xmlDoc.getElementsByTagName('title');
console.log('How many titles?', titles.length);
console.log('Second title:', titles[1].textContent); // index from 0
console.log('Last title:', titles[titles.length - 1].textContent);
// Searching inside one element only
const third = xmlDoc.getElementsByTagName('book')[2];
console.log('Author of book 3:', third.getElementsByTagName('author')[0].textContent);
// '*' matches every element
console.log('All elements:', xmlDoc.getElementsByTagName('*').length);
</script>
</body>
</html>Note: Unlike XPath, DOM collections are 0-based:
titles[0]is the first title.
querySelector() and querySelectorAll()
CSS selectors are often the shortest way to describe what you want. querySelector returns the first match (or null); querySelectorAll returns all of them.
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<library>
<book id="b1" genre="fantasy"><title lang="en">The Hobbit</title><year>1937</year></book>
<book id="b2" genre="science"><title lang="en">A Brief History of Time</title><year>1988</year></book>
<book id="b3" genre="fantasy"><title lang="es">Cien años de soledad</title><year>1967</year></book>
</library>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const show = (sel) => console.log(sel.padEnd(32), '→',
[...xmlDoc.querySelectorAll(sel)].map(e => e.textContent).join(' | ') || '(none)');
show('title');
show('book[genre="fantasy"] title');
show('title[lang="es"]');
show('book:first-child title');
show('book:last-child year');
show('[id="b2"] > title');
</script>
</body>
</html>| Selector | Matches |
|---|---|
title |
All title elements |
book title |
title anywhere inside a book |
book > title |
title that is a direct child of book |
[genre] / [genre="fantasy"] |
Has the attribute / has this value |
book:first-child, :last-child, :nth-child(2) |
Position among siblings |
By relationship
Once you have one node, you can move to its relatives:
<!DOCTYPE html>
<html>
<body>
<script>
const xml = '<library><book id="b1"><title>The Hobbit</title><year>1937</year></book><book id="b2"><title>A Brief History of Time</title><year>1988</year></book></library>';
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const year = xmlDoc.querySelector('year');
console.log('year →', year.textContent);
console.log('its parent:', year.parentNode.nodeName, year.parentNode.getAttribute('id'));
console.log('previous sibling:', year.previousElementSibling.textContent);
console.log("parent's next sibling's first child:",
year.parentNode.nextElementSibling.firstElementChild.textContent);
</script>
</body>
</html>Which method should I use?
| Situation | Best choice |
|---|---|
| All elements with one name | getElementsByTagName('name') |
| A specific element by attribute or position | querySelector(...) |
| Complex conditions (numbers, text content, parents) | XPath evaluate |
| Namespaced elements | getElementsByTagNameNS(uri, name) or XPath with a resolver |
| Neighbours of a node you already have | relationship properties |
Tip:
getElementsByTagNamereturns a live collection that updates when the document changes;querySelectorAllreturns a static snapshot. The Node List lesson explains why that matters.
Test yourself
What does xmlDoc.getElementsByTagName('book')[0] return?
- The second book
- The first book
- A count of books
- The
idof the first book
Which call finds the first title with lang="es"?
xmlDoc.getElementsByTagName('title[lang=es]')xmlDoc.querySelector('title[lang="es"]')xmlDoc.getElementById('es')xmlDoc.title.es