After XMLHttpRequest loads the XML document, use getElementsByTagName() to collect elements and read their text values.
const names = xmlDocument.getElementsByTagName('name');
const sixthName = names[5]?.textContent ?? '';
console.log(sixthName);
The original example reads the sixth <name> node. Node collections are zero-based, so index 5 is the sixth item.
const request = new XMLHttpRequest();
request.open('GET', '../php_tutorial/file-xml-demo.xml', true);
request.addEventListener('load', () => {
const xmlDocument = request.responseXML;
if (!xmlDocument) return;
const names = xmlDocument.getElementsByTagName('name');
const sixthName = names[5]?.textContent ?? '';
document.getElementById('output').textContent = sixthName;
});
request.send();
The output shown in the original tutorial is:
Alex John
<name> Values Top ↑Loop through the returned elements instead of using document.write():
const names = xmlDocument.getElementsByTagName('name');
const list = document.getElementById('name-list');
list.replaceChildren();
for (const nameElement of names) {
const item = document.createElement('li');
item.textContent = nameElement.textContent ?? '';
list.append(item);
}
document.write()? Top ↑The original examples wrote each value directly into the document. Updating an existing element with textContent or creating DOM nodes is safer for a page that has already loaded and keeps the XML data separate from HTML markup.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.