Automatic JS Broken Image Replacement

Jacob Allred
#web-dev

It’s a sad fact of life, but sometimes webpages have broken images. Wouldn’t it be nice if there were an easy way of automatically replacing these broken images?

for (i = 0; i < document.images.length; i++) {
  var img = document.images[i];
  img.onerror = function (evt) {
    this.src = "broken-image.gif";
  }
};

This snippet of JavaScript will find all your images and replace the broken ones with broken-image.gif. Pretty spiffy, huh?

You can also do something like this to apply it to individual images:

<img src="good-image.gif" onerror="this.src='broken-image.gif'">