Reputation: 1202
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);
}
}
Upvotes: 0
Views: 869
Reputation: 1787
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);
});
});
Upvotes: 0
Reputation: 2432
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.
Upvotes: 1