开发者

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

I am开发者_如何学C 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!


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


It may help you...

img=document.getElementsByTagName("img");
for(i=0; i<img.length; i++) {
    imgp = imgp + img[i].src + '<br/>'; 
}
document.write(imgp);


I searched the whole web for a solution to this, maybe this will help if someone else searches the same.

for(var i = 0; i< document.images.length; i++){
document.images[i].style.border = "1px solid #E0FDA6";
}

Meaning, search all images that have style tag (border in this example) and set all borders to E0FDA6 (useful to reset single highlighted images), but I guess it can be used for everything with style tag.

Rg, Anjanka


To print on current page (replace content):

document.write(`<pre>${JSON.stringify(Array.prototype.map.call(document.getElementsByTagName("img"), img => img.src), null, 2)}</pre>`);

To save in array:

const imgs = Array.prototype.map.call(document.getElementsByTagName("img"), img => img.src);

To just console dir/log directly:

console.dir(Array.prototype.map.call(document.getElementsByTagName("img"), img => img.src));
console.log(Array.prototype.map.call(document.getElementsByTagName("img"), img => img.src));


Make it simple:

console.log(document.body.getElementsByTagName('img'));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜