Remove Images That Are Not Found using HTML
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"  
     onerror="this.remove()" 
/>

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.