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>
This application uses the same sample XML file and the same XML element-reading approach as the original tutorial. It also uses getElementsByTagName().
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().
Demo of displaying a dropdown list from XML
<!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>
Next, create a dropdown list where selecting one student displays that student's id, name and class.
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.