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

前端 未结 5 1364
感动是毒
感动是毒 2021-02-08 03:26

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].sr         


        
相关标签:
5条回答
  • 2021-02-08 03:31

    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

    0 讨论(0)
  • 2021-02-08 03:36

    Make it simple:

    console.log(document.body.getElementsByTagName('img'));
    
    0 讨论(0)
  • 2021-02-08 03:44

    It may help you...

    img=document.getElementsByTagName("img");
    for(i=0; i<img.length; i++) {
        imgp = imgp + img[i].src + '<br/>'; 
    }
    document.write(imgp);
    
    0 讨论(0)
  • 2021-02-08 03:45

    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));
    
    0 讨论(0)
  • 2021-02-08 03:58

    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;
    }
    
    0 讨论(0)
提交回复
热议问题