Check if img src is valid using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 6, 2022

banner

Check out my new book

Check if img src is valid using JavaScript #

To check if an img src is valid:

  1. Add an error event listener on the img element.
  2. If the src is invalid, set it to a backup image.
  3. Alternatively, hide the image.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <img id="img" src="https://example.com/does-not-exist.jpg" alt="banner" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const img = document.getElementById('img'); img.addEventListener('error', function handleError() { console.log(img.src); // 👇️ if set to non-existent image, causes infinite loop // img.src = 'backup.webp'; // 👈️ must be a valid image });

We set an error event listener on the image element.

When an image's source fails to load, an error event is fired at the element that initiated the load.

When the error event is fired, the handleError function gets invoked.

You could set the image's src property to a backup image or hide the image.

Note that if you set the image's src property to an invalid image, it will trigger the error event again and cause an infinite loop.

An alternative approach is to hide the image if it fails to load.

index.js
img.addEventListener('error', function handleError() { console.log(img.src); img.style.display = 'none'; });

In this example, we set the image's display property to none, which hides the image.

Alternatively, you can set the image's visibility property to hidden, which would make the image invisible, but still take space on the page.

index.js
const img = document.getElementById('img'); img.addEventListener('error', function handleError() { console.log(img.src); img.style.visibility = 'hidden'; });

When an element's visibility property is set to hidden, it still takes up space on the page, however the element is invisible (not drawn). It still affects the layout on your page as normal.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.