Reputation: 325
I don't know if I'm having a syntax error but the compiler is giving me
TypeError: 'undefined' is not an object (evaluating 'xmlDoc.getElementsByTagName("icon")[count].childNodes')
Its me giving me this problem when im parsing the XML
from my server
, my actual javascript code is like this
var xmlDoc = Obj.responseXML;
var count = 0;
if(xmlDoc){
while(count <= xmlDoc.getElementsByTagName("item").length){
document.getElementById("flow").innerHTML += "<div class='item'><img class='content' src='" + xmlDoc.getElementsByTagName("icon")[count].childNodes[0].nodeValue.replace(/\s+$/g,' ') +"' /></div>";
count++;
}
}else{
alert("Unable to parse!");
}
and my XML goes like this.
<feed>
<item>
<title>Given Title</title>
<icon>
http://i178.photobucket.com/albums/w255/ace003_album/Logo-ETC-RGB-e1353503652739.jpg
</icon>
</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</feed>
i just want to parse the image link and to show it. DOM parser
var url = "http://myURL.com/document.xml";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
Obj = new XMLHttpRequest();
}
else
{
Obj = new ActiveXObject("Microsoft.XMLHTTP");
}
Obj.open("POST",url,false);
Obj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Obj.send();
Upvotes: 0
Views: 984
Reputation: 64536
Firstly, you're while loop condition should be just <
not <=
. By using the latter, the loop is running one too many times, causing the error because the index is out of bounds.
Secondly, in the while loop you're getting the icon
elements based on the count
from the root of the document. The icon
's are children of each item
so you should retrieve the icon
relative to the item
by using item.getElementsByTagName('icon')[0]
not xmlDoc.getElementsByTagName('icon')[count]
.
Not related to the problem but building HTML as strings like that is undesirable. Creating the elements and inserting them into the DOM would be better because you don't need to handle any escaping. Also, store a reference to flow
before the while, instead of finding it on each iteration.
var div;
var img;
var flow = document.getElementById('flow');
var items = xmlDoc.getElementsByTagName("item");
while(count < items.length){
div = document.createElement('div');
div.className = 'item';
img = document.createElement('img');
img.className = 'content';
img.src = items[count].getElementsByTagName("icon")[0].childNodes[0].nodeValue.replace(/\s+$/g,' ');
div.appendChild(img);
flow.appendChild(div);
count++;
}
Upvotes: 1