Create a Dropdown List from XML Data

The original XML example builds a dropdown where each student's id is the option value and the student's name is the visible label.

<select name="id">
  <option value="5">Alex John</option>
</select>
Table of Contents

Load the XML Data Top ↑

This application uses the same sample XML file and the same XML element-reading approach as the original tutorial. It also uses getElementsByTagName().

Build the Dropdown Options Top ↑

const names = xmlDocument.getElementsByTagName('name');
const ids = xmlDocument.getElementsByTagName('id');
select.replaceChildren();

for (let i = 0; i < names.length && i < ids.length; i += 1) {
  const option = new Option(names[i].textContent ?? '', ids[i].textContent ?? '');
  select.add(option);
}

Using the native Option constructor avoids building HTML strings and then inserting them with document.write().

Working Demo Top ↑

Demo of displaying a dropdown list from XML

Complete Working Source Top ↑

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>XML dropdown demo</title>
</head>
<body>
  <label for="student-list">Student</label>
  <select id="student-list" name="id"></select>
  <p id="status" aria-live="polite"></p>

  <script>
    const select = document.getElementById('student-list');
    const status = document.getElementById('status');
    const request = new XMLHttpRequest();

    request.open('GET', '../php_tutorial/file-xml-demo.xml', true);
    request.addEventListener('load', () => {
      const xmlDocument = request.responseXML;
      if (!xmlDocument) {
        status.textContent = 'The XML response could not be parsed.';
        return;
      }

      const names = xmlDocument.getElementsByTagName('name');
      const ids = xmlDocument.getElementsByTagName('id');
      select.replaceChildren();

      for (let i = 0; i < names.length && i < ids.length; i += 1) {
        const option = new Option(names[i].textContent ?? '', ids[i].textContent ?? '');
        select.add(option);
      }

      status.textContent = `${select.options.length} students loaded.`;
    });
    request.addEventListener('error', () => {
      status.textContent = 'Unable to load the XML file.';
    });
    request.send();
  </script>
</body>
</html>

Use the Selected Student in a Form Top ↑

Next, create a dropdown list where selecting one student displays that student's id, name and class.

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