passwd
passwd

Reputation: 3353

JavaScript delete all unique images on the page

I am trying to make userscript that will delete all unique images on a certain page. So I need to compare all the links and delete every unique. I am trying to do it in this way:

var images = document.getElementsByTagName('img');

for(i = 0;i < images.length; i++){
   for(j = 0;j < images.length; j++){
       if(images[i].src.!(match(images[j])) images[i].remove()
}

Or hide it with "display:none"

Upvotes: 0

Views: 58

Answers (3)

Natsathorn
Natsathorn

Reputation: 1528

This is look similar to your code.

var images = document.getElementsByTagName("img");
var arr = [];
for(x in images){
    If(arr.indexOf(images[x].src) == -1){
           arr.push(images[x].src);
    }else
            images[x].style.display = "none";
    }
}

Upvotes: 0

Alex Kudryashev
Alex Kudryashev

Reputation: 9460

    function hideUnique() {
        var imgs = document.getElementsByTagName('img');
        var srcs = [];
        for (var i = 0, n = imgs.length; i < n; i++) {
            srcs[imgs[i].src] = (srcs[imgs[i].src] || 0) + 1;
        }
        for (var i = 0, n = imgs.length; i < n; i++) {
            if (srcs[imgs[i].src] == 1)
                imgs[i].style.display = 'none';
        }

    }

Upvotes: 1

Haizhou Liu
Haizhou Liu

Reputation: 491

You can try this

var images = document.getElementsByTagName("img");
var imageSrcMap = {};

for(var i = 0; i < images.length; i++){
  if(!imageSrcMap[images[i].src]){
    imageSrcMap[images[i].src] = {
      count:0,
      position:[]
    }
  }  
  imageSrcMap[images[i].src].count++;
  imageSrcMap[images[i].src].position.push(i);
}

Object.keys(imageSrcMap).forEach(function(src){
  if(imageSrcMap[src].count === 1){
    images[imageSrcMap[src].position[0]].style.display = 'none';
  }
});

Upvotes: 0

Related Questions