...

View Full Version : ...getElementById looping with XML...



danh
02-28-2005, 11:08 PM
hello,

i am fairly new to javascript and XML. i'm trying to loop through some nodes and drop the output into a series of DIVs using getElementById. here's the code for that:

<script language="JavaScript" type="text/JavaScript">
function showCalendar(){
if (document.implementation && document.implementation.createDocument)
{
xmlDoc = document.implementation.createDocument("","",null)
}
else if (window.ActiveXObject)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}
else
{
alert('Your browser can\'t handle this script');
return;
}
xmlDoc.async=false;
xmlDoc.load("calendar.xml");

var days = xmlDoc.getElementsByTagName("day");

for (var i=0; i<days.length; i++) {
var calevent = days[i].getElementsByTagName("event")[0].childNodes[0].nodeValue;
document.getElementById("event"+i).innerHTML = calevent;
}
}
</script>

and here is the XML (very basic):

<?xml version="1.0" encoding="UTF-8"?>
<calendar>
<day>
<date>1</date>
<event>Event for the 1st</event>
<link>http://www.eventlink.com</link>
</day>
<day>
<date>2</date>
<event>Event for the 2nd</event>
<link>http://www.eventlink.com</link>
</day>
<day>
<date>3</date>
<event>Event for the 3rd</event>
<link>http://www.eventlink.com</link>
</day>
</calendar>
the part that is not working is document.getElementById("event"+i).innerHTML = calevent;. the error i'm getting is "...getElementById("event"+i)... has no properties", which tells me that the loop is not working correctly. but when i document.write(calevent) the loop works fine and outputs the XML. that doesn't suit my purposes. what i'm trying to do is loop through the nodes, grab the data and then flow it into a series of DIVs on the page (event1, event2, event3, etc.).

the function loads onload from the body tag. the rest of the page is written in ASP.

please advise.

thanks for your time,
dan.

glenngv
03-01-2005, 04:51 AM
what i'm trying to do is loop through the nodes, grab the data and then flow it into a series of DIVs on the page (event1, event2, event3, etc.).

If the divs have ids of event1, event2, event3 ..., then you should add 1 to i as i starts at 0.

document.getElementById("event"+(i+1)).innerHTML = calevent;

danh
03-01-2005, 04:30 PM
glenngv,

thanks! i narrowed down the problem to the fact that the iteration was starting at 0 and the calendar starting at 1, but i couldn't see the answer!

thanks again,
dan.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum