banjocode Remove Images That Are Not Found using HTML

Remove Images That Are Not Found using HTML

Sometimes you might want to fetch a photo dynamically, if that fails you most likely would want to remove it or replace it with another picture. This is how.

1 min read

Removing a broken image

HTML allows you to basically add a onerror attribute to the image tag, in which you can either remove or replace the image you are trying to show.

To remove the image if you cannot find it, simply use this.remove(). In this particular case, this refers to the actual HTML element.

<img src="/somePicture.jpg"  

If you want to display a fallback image instead, you can use this snippet;

<img src="/somePicture.jpg" 
     onerror="this.onerror=null; this.src='anotherPicture.jpg'" 

Thanks to Flavio Copes, for showing this neat trick.