This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
This chapter demonstrates some HTML applications using XML, HTTP, DOM, and JavaScript.
In this chapter we will use the XML file called "cd_catalog.xml".
This example loops through each <CD> element, and displays the values of the <ARTIST> and the <TITLE> elements in an HTML table:
<table id="demo"></table> <script> function loadXMLDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { const xmlDoc = xhttp.responseXML; const cd = xmlDoc.getElementsByTagName("CD"); myFunction(cd); } xhttp.open("GET", "cd_catalog.xml"); xhttp.send(); } function myFunction(cd) { let table="<tr><th>Artist</th><th>Title</th></tr>"; for (let i = 0; i < cd.length; i++) { table += "<tr><td>" + cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "</td><td>" + cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "</td></tr>"; } document.getElementById("demo").innerHTML = table; } </script>
For more information about using JavaScript and the XML DOM, go to DOM Intro.
This example uses a function to display the first CD element in an HTML element with id="showCD":
const xhttp = new XMLHttpRequest(); xhttp.onload = function() { const xmlDoc = xhttp.responseXML; const cd = xmlDoc.getElementsByTagName("CD"); myFunction(cd, 0); } xhttp.open("GET", "cd_catalog.xml"); xhttp.send(); function myFunction(cd, i) { document.getElementById("showCD").innerHTML = "Artist: " + cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "<br>Title: " + cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "<br>Year: " + cd[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue; }
To navigate between the CDs in the example above, create a
and function:function next() { // display the next CD, unless you are on the last CD if (i < len-1) { i++; displayCD(i); } } function previous() { // display the previous CD, unless you are on the first CD if (i > 0) { i--; displayCD(i); } }
The last example shows how you can show album information when the user clicks on a CD:
function displayCD(i) { document.getElementById("showCD").innerHTML = "Artist: " + cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue + "<br>Title: " + cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "<br>Year: " + cd[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue; }
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon