DEV Community

Tomoyuki Aota
Tomoyuki Aota

Posted on • Edited on

Replacing <img> with <div> when img.onerror is called

(A Japanese translation is available here.)

When img.onerror is called, there are several options instead of leaving the broken image:

  • Replace img.src to set a different image
  • Set img.style.display = 'none' to remove the element from DOM

References:

In my case, I wanted to replace <img> with <div>. I googled for a while but couldn't find the way. I did some experiments and found that configuring img.outerHTML does the trick.

In the code above, targetImage.outerHTML = "<div>Invalid Image!</div>"; is set.
Configuring style for the <div> will make it prettier.

As an actual example, I'm developing Photo Data Viewer. This is an app to check Exif data of a photo. When the file other than photos is selected (i.e. files cannot be displayed with <img>), it displays "Unsupported File Format" using <div> instead of a photo.
The code is here.
This app uses Next.js, so the code to set onerror looks different, but setting outerHTML is the same.

I hope it helps!

Top comments (0)