Search code examples
jqueryarraysinternet-explorer-8pushtagname

IE8 Unable to get value of the property 'src': object is null or undefined


This has been stressing me out for 3 nights now...I don't know why it works in IE9 but not IE8. I keep getting this error when I run it on IE8:

SCRIPT5007: Unable to get value of the property 'src': object is null or undefined

when I try to debug I get this line being the cause ->

        var map_locations = [], container = document.getElementById('renting-map-js'), 
        c = container.children, l = c.length, i, obj, p, m, j;

        //loop through all child nodes
        for ( i = 0; i < l; i++) {
            obj = {};

            //highlights this line
            obj.img = c[i].getElementsByTagName('img')[0].src; 

            p = c[i].getElementsByTagName('p');
            m = p.length;
            for ( j = 0; j < m; j++)
                obj[p[j].className] = p[j].firstChild.nodeValue;
            map_locations[i] = obj;
            console.log(obj);
        }

Here is the Fiddle http://jsfiddle.net/EgzKv/


Solution

  • In IE6-8, .children also returns comment nodes. Since comment nodes can't have children, they also can't contain images that have a src attribute, causing your error.

    jQuery can fix this:

    var map_locations = [],
        container = document.getElementById('renting-map-js'),
        c = $(container).children().get(),
        l = c.length,
        i, obj, p, m, j;
    
    //loop through all child nodes
    for (i = 0; i < l; i++) {
        obj = {};
        obj.img = c[i].getElementsByTagName('img')[0].src;
        p = c[i].getElementsByTagName('p');
        m = p.length;
        for (j = 0; j < m; j++)
        obj[p[j].className] = p[j].firstChild.nodeValue;
        map_locations[i] = obj;
        console.log(obj);
    }​