passwd passwd - 6 months ago 9
Javascript Question

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"

Answer

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';
  }
});
Comments