views:

29

answers:

2

hi, i'm trying to loop through all images on the page, should be easy but i can't see where im going wrong here. the imgs gets populated with the images but the imgs.length returns 0; its somethign stupid but i just cant figure it out.

var imgs = document.getElementsByTagName('img');
console.log(imgs);
console.log(imgs.length);

if(imgs != null){
    //console.log('in loop');
    for(i=0; i<imgs.length; i++){
        console.log(imgs.item(i).src);
    }
}
+1  A: 

As Nick says, the script should be runned after the images are loaded. If the script's in the header it won't work as the images aren't loaded yet.

kaklon
A: 
window.onload = function () {

 var imgs = document.getElementsByTagName('img');// or document.images;

 console.log(imgs.length);

 if(imgs.length > 0){
    for(var i=0; i<imgs.length; i++){
        console.log(imgs[i].src);
    }
 }
};

jQuery

$(document).ready(function () { 
     console.log($('imgs').length);

     $('imgs').each(function(i, img){
            console.log(img.src);
     });
});
Q_the_dreadlocked_ninja
Kudos for including "plain ol' JS" first. If you're going to show the jQuery equivalent for kicks, then why not update the entire function body to take advantage? `$('img').each(function(index, img) { console.log(img.src); });`
Ken
@Ken - Very neat, thanks.
Q_the_dreadlocked_ninja