Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the image sources on a particular Page using Javascript

I am using a simple script to find an image on a page and get its source.

function img_find() {
    var img_find2 = document.getElementsByTagName("img")[0].src;
    return img_find;
}

However when I go to write this function on my page it only finds the first image and then stops. What is the best way to have it print all of the image src's on the current page? Thanks!

like image 986
Chris Avatar asked Apr 27 '11 18:04

Chris


2 Answers

You indeed told the code to do so. Don't do that. Just tell it to loop over all images and push the src of each in an array and return the array with all srcs instead.

function img_find() {
    var imgs = document.getElementsByTagName("img");
    var imgSrcs = [];

    for (var i = 0; i < imgs.length; i++) {
        imgSrcs.push(imgs[i].src);
    }

    return imgSrcs;
}
like image 155
BalusC Avatar answered Oct 20 '22 00:10

BalusC


It may help you...

img=document.getElementsByTagName("img");
for(i=0; i<img.length; i++) {
    imgp = imgp + img[i].src + '<br/>'; 
}
document.write(imgp);
like image 26
Ashish Kumar Avatar answered Oct 19 '22 23:10

Ashish Kumar