Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript getAttribute not working

Tags:

javascript

var objects = document.getElementsByTagName('object');
for (var i=0, n=objects.length;i<n;i++) {
    objects[i].style.display='none';
    var swfurl;
    var j=0;
    while (objects[i].childNodes[j]) {
    if (objects[i].childNodes[j].getAttribute('name') == 'movie') {
            /* DO SOMETHING */ 
    }
    j++;
}
    var newelem = document.createElement('div');
    newelem.id = '678297901246983476'+i;
    objects[i].parentNode.insertBefore(newelem, objects[i]);
    new Gordon.Movie(swfurl, {id: '678297901246983476'+i, width: 500, height: 400});
}

It says that getAttribute is not a function of childNodes[j]. What's wrong? I don't see the point.

like image 626
icant Avatar asked Jul 13 '26 05:07

icant


1 Answers

Remember that childNodes includes text nodes (and comment nodes, if any, and processing instructions if any, etc.). Be sure to check the nodeType before trying to use methods that only Elements have.

Update: Here in 2018, you could use children instead, which only includes Element children. It's supported by all modern browsers, and by IE8-IE11. (There are some quirks in older IE, see the link for a polyfill to smooth them over.)

like image 97
T.J. Crowder Avatar answered Jul 14 '26 17:07

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!