Chrome says Cannot read property 'nodeName' of undefined, IE6 is fine, using Google Map API

Sivakanesh picture Sivakanesh · Jun 4, 2010 · Viewed 23.4k times · Source

I have an XML file in the following structure.

<NewDataSet>
 <markers>
  <name>name text</name>
  <desc>desc text</desc>
  <Lat>57.149328033771</Lat>
  <Long>-2.12561060173764</Long>
  <cost>9985</cost>
 </markers>
</NewDataSet>

I'm using Google Map API to parse and map these, using the following Javascript.

 function load() {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(47.614495, -122.341861), 13);

    GDownloadUrl("test1.xml", function(data) {
        var xml = GXml.parse(data);
        x= xml.documentElement;
        y = xml.documentElement.childNodes;
        alert(y.length);
        for (i=0;i<y.length;i++)
        {
            if (y[i].nodeType!=3)
            {
              alert(y[i].childNodes[0].nodeName + " : " + y[i].childNodes[0].childNodes[0].nodeValue); //name
            }
        }

    });
  }
}

Both the full xml and html files can be downloaded here: http://domain2405544.sites.fasthosts.com/test/test1.htm http://domain2405544.sites.fasthosts.com/test/test1.xml

First off, I'm just trying to parse this data. Works fine in IE6 (no choice with that) and it alerts the data correctly. However when I load the same page in Chrome is tells me:

Uncaught TypeError: Cannot read property 'nodeName' of undefined - line 29

I'm using identical files, so may be there is an underlying problem I just can't see. Has anyone got any ideas why this may be happening?

Thanks

Answer

Tim Down picture Tim Down · Jun 4, 2010

What is happening is that you're trying to get children of a text node. Chrome will have a text node prior to the <name> child of the <markers> element whereas IE won't.

You're testing whether each child of the document element <NewDataSet> is a text node, thus avoiding the problem at that level, but you're assuming the first child of each <markers> element is the <name> element when in fact it's a text node in non-IE browsers.

You'd be better off using the getElementsByTagName of DOM nodes to avoid this problem. Here's an improved version:

GDownloadUrl("test1.xml", function(data) {
    var xml = xhr.responseXML;
    var root = xml.documentElement;
    var markers = root.getElementsByTagName("markers"), nameEl;

    for (var i = 0, len = markers.length; i < len; ++i) {
        nameEl = markers[i].getElementsByTagName("name")[0];
        alert(nameEl.firstChild.data);
    }
});