javascript images array – Education Career Blog

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);
    }
}

,

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.

,

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(imgsi.src);
    }
 }
};

jQuery

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

     $('imgs').each(function(i, img){
            console.log(img.src);
     });
});

Leave a Comment