Javascript – see if src of img exists


when I place an img tag I create the src attribute dynamically. Is there a way of testing if the src (path where the image is located) actually exists with javascript in order to avoid getting:

enter image description here

Best Solution

You can use the error event:

var im = document.getElementById('imageID'); // or select based on classes
im.onerror = function(){
  // image not found or change src like this as default image:

   im.src = 'new path';

Inline Version:

<img src="whatever" onError="this.src = 'new default path'" />


<img src="whatever" onError="doSomething();" />

<img> tag supports these events:

  • abort (onAbort)
  • error (onError)
  • load (onLoad)

More Information: