0

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);
    }
}
3
  • When does this code run? Commented Oct 15, 2010 at 11:18
  • 1
    if(imgs != null){ is incorrect; imgs will always be an array, but it just might be empty. Change it to if(imgs.length){. This won't solve your problem, but just for future reference. Commented Oct 15, 2010 at 11:21
  • thanks i'll check that out, figured it out, i was calling it in a script at the top before images are loaded, just changed it to call onload of body and it works. the codes for a bookmarklet so shouldn't matter but just wasn't working in testing. sorry for the stupid question Commented Oct 15, 2010 at 11:25

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.