Search code examples
javascriptimagebookmarklet

How to find all .jpg, .png and .gif and list them into a grid with JavaScript?


I would like to build a basic bookmarklet that finds all .jpg, .png and .gif images of a web page and list them into a grid. (e.g. 4 images in a row) I just found this snippet but it pushes all image no matter of the extension:

var images = document.getElementsByTagName('img'); 
var srcList = [];
for(var i = 0; i < images.length; i++) {
    srcList.push(images[i].src);
}

How to do it?


Solution

  • You could use the querySelectorAll and use a regular expression to get the images with the extensions:

    var images = document.querySelectorAll('img[src$=".jpg"], img[src$=".png"], img[src$=".gif"]');
    var srcList = [];
    for(var i = 0; i < images.length; i++) {
        srcList.push(images[i].src);
    }
    

    To generate a list of images you could do:

    for(var i = 0; i < images.length; i++) {
        var img = document.createElement('img');
        img.src = images[i].src;
        document.body.appendChild(img);
    }
    

    You have to add some CSS to make it a grid.