I am trying to use a for loop to iterate through an XML document and place the data in the webpage. What I want this code to do is take the first 4 entries in the XML and display their title, date, time and description. The code I currently have looks like this.
<script type="text/javascript">
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","events.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var i = 0;
for( i = 0; i <4; i++){
document.write("<div style=\"display:block;padding-left:5px;\">");
document.write("<br/>");
document.write("<strong>What:</strong> <span id=\"title\"> </span>");
document.write("<br/>");
document.write("<strong>When:</strong> <span id=\"date\"></span> @ <span id=\"time\"></span>");
document.write("<br/>");
document.write("<strong>Description:</strong> <span id=\"descr\"></span><br/></div>");
document.getElementById("title").innerHTML = xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue;
document.getElementById("date").innerHTML = xmlDoc.getElementsByTagName("date")[i].childNodes[0].nodeValue;
document.getElementById("time").innerHTML =xmlDoc.getElementsByTagName("time")[i].childNodes[0].nodeValue;
document.getElementById("descr").innerHTML =xmlDoc.getElementsByTagName("descr")[i].childNodes[0].nodeValue;}
</script>
And the incorrect output looks like this.
What: Relay for Life Bingo When: N/A @ N/A Description: N/A What: When: @ Description: What: When: @ Description: What: When: @ Description:
The first entry is not correct because it is the fourth element in the XML file and as you can see the rest is blank. I am new to XML so this is probably some beginners mistake but I would appreciate some feedback on how to get this to work.
events.xml
<event>
<title>Relay for Life Wristband Sale</title>
<date>March 26 & 28 </date>
<time>11 A.M - 3 P.M.</time>
<descr>N/A</descr>
</event>
<event>
<title>SHPE/SWE/EC/IEEE Dodgeball Event</title>
<date>April 1 </date>
<time>N/A</time>
<descr>N/A</descr>
</event>
<event>
<title>CH2MHILL Social/GBM</title>
<date>April 2</date>
<time>N/A</time>
<descr>N/A</descr>
</event>
<event>
<title>Relay for Life Bingo</title>
<date>N/A</date>
<time>N/A</time>
<descr>N/A</descr>
</event>
<event>
<title></title>
<date></date>
<time></time>
<descr></descr>
</event>
<event>
<title></title>
<date></date>
<time></time>
<descr></descr>
</event>
<event>
<title></title>
<date></date>
<time></time>
<descr></descr>
</event>
idof each tag, in your code you are replacing the first set of values while every time iterating the loop. You selecting the element with id'stitledateand so.They are same in all the element , They must be unique.