Displaying XML Element Values with JavaScript

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);
Table of Contents

Read One XML Element Top ↑

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

Display All <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);
}

Why Use DOM Output Instead of 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.

Use the XML Data Top ↑

The same XML data can be used to create a dropdown list box for a form.

Reading Attributes

XML




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer