Question

I'm trying to create a bookmarklet that will hide images on any page I'm currently viewing. It works for removing <img> tags and it creates a CSS style that tries to hide all background images. The issue I keep encountering are background images that are specified with !important. I can't figure out how to hide them.

Here is a codepen demonstrating the issue: http://codepen.io/Chevex/pen/kbDcv

If you remove the !important from the background image then it all works fine. Any ideas?

Was it helpful?

Solution 3

you can hide divs with backgrounds in the same manner as you do img tags in the linked code:

var imgs=document.querySelectorAll("div[style*='background']");
for (var i=0;i<imgs.length;i++) {
   imgs[i].style.visibility="hidden";
}

OTHER TIPS

Make sure your CSS occurs after that CSS on the page and put the !important override on your CSS. Also, since you specify that you are using JavaScript, you can add your CSS as inline CSS on the actual element and use !important. The only thing that overrides inline important is user agent user important style sheets.[reference][example]

As others have pointed out, you can use the newer (IE9+) querySelectorAll function:

function hideImages() {
  var d = document,s = window.getComputedStyle;
  Array.prototype.forEach.call(
    d.querySelectorAll("body *"),
    function(el){
      if (s(el).backgroundImage.match(/url/) || 
         el.tagName === 'IMG'){
          el.style.visibility="hidden";
      }
    }
  );
}

$('button').click(hideImages);

http://codepen.io/anon/pen/rBnIx

Updated to include background-images set via CSS.


Though, you could probably lose a lot by turning anything with a background-image invisible. You might have better luck just turning that property off. You could either check the computed style of each element like above or just set them all like below. The function below uses setProperty to override !important which is also IE9+.

function hideImages() {
  var a=document.querySelectorAll("body *"),i=a.length;
  function _f(n){
         if (n.tagName === 'IMG') n.style.visibility="hidden";
         n.style.setProperty("background-image", "none", "important");
  };
  while(--i) _f(a[i]);
}

http://codepen.io/anon/pen/tnrdH

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