Question

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?

Was it helpful?

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.

OTHER TIPS

Simple way is to filter the array

    var images = document.getElementsByTagName('img');
    var srcList = [];
    for (var i = 0; i < images.length; i++) {
        var im = images[i];
        var src = im.src;
        var ext = src.substring(lastIndexOf('.'));
        if (ext == '.jpg' || ext == '.png' || ext == '.gif') {
            srcList.push(images[i].src);
        }
    }

By the way, using querySelectedAll is far more elegant solution as mentioned in comments..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top