-1

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?

Tom
  • 5,588
  • 20
  • 77
  • 129

2 Answers2

3

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.

putvande
  • 15,068
  • 3
  • 34
  • 50
  • Thanks for your example! Do you have also an idea on how to generate a HTML grid with the srcList image paths? (So you can see them all) – Tom May 14 '14 at 14:12
0

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