This chapter demonstrates some small XML applications built on XML, HTML, XML DOM and JavaScript.
In this application, we will use the "cd_catalog.xml" file.
The following example gets the XML data from the first CD element and then displays the data in the HTML element with id="showCD". The displayCD() function is called when the page loads:
x=xmlDoc.getElementsByTagName("CD"); i=0; function displayCD() { artist=(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue); title=(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue); year=(x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue); txt="Artist: " + artist + "<br />Title: " + title + "<br />Year: "+ year; document.getElementById("showCD").innerHTML=txt; }
Try it »
In order to add navigation (functionality) to the above example, two functions need to be created: next() and previous():
function next() { // display the next CD, unless you are on the last CD if (i<x.length-1) { i++; displayCD(); } } function previous() { // displays the previous CD, unless you are on the first CD if (i>0) { i--; displayCD(); } }
Try it »
The final example shows how to display album information when the user clicks on a CD item:
Give it a try.
To learn more about using JavaScript and the XML DOM, visit our XML DOM tutorial.