Search code examples
javascriptxmlhtmlxml-parsinggetelementsbytagname

getElementsByTagName 'undefined' in Firefox and Chrome?


I am having a problem with getElementsByTagName. I am trying to pull information from an xml file I received from the server using ajax. In IE it is works fine, but when I try to run it on Chrome or FireFox I get an "undefined".

Javascript:

function parseMessage()
{
    doc = request.responseXML;
    sum = "";

    for (var i=0; i< doc.getElementsByTagName('coupon').length; i=i+1)
    {
        var lat2 = doc.documentElement.getElementsByTagName('latitude').item(i).text;
        var longi2 = doc.documentElement.getElementsByTagName('longitude').item(i).text;
        var latlng  = new google.maps.LatLng( lat2 , longi2 ); 
        var product =  doc.documentElement.getElementsByTagName('productname').item(i).text;
        // marker[i] = createMarker(map2, product, latlng, description);

        sum = sum + description+ " "+ product + lat2 + longi2;                          
    }

    document.write(sum);
}           

XML:

<?xml version="1.0" encoding="UTF-8"?>
-<coupons>
-<coupon id="1">
<productname>Bigmac</productname>
<companyname>Macdonalds</companyname>
<latitude>32.015954</latitude>
<longitude>34.755228</longitude>
</coupon>
-<coupon id="2">
<productname>Crocs</productname>
<companyname>Crocs</companyname>
<latitude>32.079375</latitude>
<longitude>34.769325</longitude>
</coupon>
-<coupon id="3">
<productname>Nike Shoks</productname>
<companyname>NIKE</companyname>
<latitude>32.048825</latitude>
<longitude>34.785461</longitude>
</coupon>
-<coupon id="4">
.....

Solution

  • The first problem is that getElementsByTagName() returns a list of elements; which can't be operated on as a group, so you'd have to select a particular node on which to work:

    getElementsByTagName('latitude')[0]; // for the first element.
    

    The second problem is that:

    getElementsByTagName('latitude')[0].item(i);
    

    Should be used to access a property, or attribute, of a particular element, and item(i) is neither, though it may be set/used somewhere that we're not seeing.

    If you're trying to access one of the element's children (and in your posted code the latitude elements don't have any children), you could use:

    getElementsByTagName('latitude')[0].childNodes[i];
    

    And text() doesn't return, or do, anything in plain JavaScript. If you're using the jQuery text() method, then that only works on jQuery objects, if you're trying to access the text content of the current nodes, then:

    getElementsByTagName('latitude')[0].textContent; // for Firefox, Chrome...
    

    Or:

    getElementsByTagName('latitude')[0].innerText; // for IE