0

I was trying to get all the images from a webpage and display them in the console log Code below:

function img_find() 
{
    var imgs = document.getElementsByTagName("img");
    var imgSrcs = [];
    for (var i = 0; i < imgs.length; i++){
      imgSrcs.push(imgs[i].src);
      console.log(imgs[i].src);
    }`
    return imgSrcs;
}

But now I just want to get gif images only. How can I do that?

Akoba
  • 1

2 Answers2

1
function img_find() {
var images = document.getElementsByTagName('img'); 
var srcList = [];
for(var i = 0; i < images.length; i++) {
    if(!!(images[i].src).match(/\w+\.(gif)$/gi))
        srcList.push(images[i].src);
}

console.log(srcList);
}

You must be wondering as to why I used !! (double not operator) in the if condition. You can read about it here, they explained it better than I could: What is the !! (not not) operator in JavaScript?

Hackinet
  • 3,252
  • 1
  • 10
  • 22
0

You can split and compare the extension in the src , here is how it's done (with regex).

function img_find() 
{
    var imgs = document.getElementsByTagName("img");
    var imgSrcs = [];
    for (var i = 0; i < imgs.length; i++){
      if (imgs[i].src.toLocaleLowerCase().split(/\.(?=[^\.]+$)/) == "gif"){
          imgSrcs.push(imgs[i].src);
      }          
      console.log(imgs[i].src);
    }
    return imgSrcs;
}
Ahmed Tag Amer
  • 1,381
  • 1
  • 8
  • 21