Skip to main content

How to Check if an Image src is Empty or Invalid in JavaScript

When working with images in the DOM, two common issues arise: an <img> tag might be missing its src attribute entirely, or the src attribute might point to a broken link that fails to load. Handling these cases gracefully is essential for a good user experience.

This guide will teach you the correct methods for detecting both of these scenarios. You will learn how to check for a missing src attribute and how to use the error event listener to catch invalid images and replace them with a fallback.

The Core Problem: Empty src vs. Invalid src

It is crucial to distinguish between these two different problems:

  • Empty src: The <img> tag exists, but its src attribute is either not set or is an empty string.
  • Invalid src: The src attribute is set, but the URL points to a resource that cannot be loaded (e.g., a 404 error).

Problem:

<!-- Problem 1: The src attribute is missing -->
<img id="imgEmpty" alt="An empty image">

<!-- Problem 2: The src points to a broken link -->
<img id="imgInvalid" src="https://example.com/non-existent-image.jpg" alt="An invalid image">

We need different techniques to handle each of these cases.

Checking if an src Attribute is Empty or Missing

The most reliable way to check if the src attribute has not been set is to use the element.getAttribute() method.

The logic: The getAttribute('src') method reads the raw value of the HTML attribute.

  • If the src attribute is not present, it returns null.
  • If the src attribute is present but empty (e.g., src=""), it returns an empty string "".

Both null and "" are "falsy" values in JavaScript, so we can check for them with a simple if (!src) condition.

Solution:

const img = document.getElementById('imgEmpty');
const src = img.getAttribute('src');

console.log(src); // Output: null

if (!src) {
console.log('The image src attribute is empty or missing.');
} else {
console.log('The image src attribute has a value.');
}
// Output: The image src attribute is empty or missing.
note

Using the .src property (img.src) is not reliable for this check, as browsers will often resolve a missing src to the page's own URL, which is not what you want to check for.

Checking if an src is Invalid (Broken Image)

To detect a broken image link, you cannot check the src value itself. Instead, you must listen for the error event, which the browser fires on an <img> element if it fails to load the specified image.

Solution:

const img = document.getElementById('imgInvalid');

img.addEventListener('error', function handleError() {
console.log('The image could not be loaded.');
// Take an action, like hiding the image or showing a fallback.
});

Handling the Error by Hiding the Image

A simple and clean way to handle a broken image is to hide it so the user doesn't see a broken image icon.

const img = document.getElementById('imgInvalid');

img.addEventListener('error', function handleError() {
console.log('Image failed to load. Hiding it.');
img.style.display = 'none';
});
note

Setting display to none removes the element from the document layout completely. Alternatively, img.style.visibility = 'hidden' would make it invisible but keep its allocated space in the layout.

Handling the Error by Setting a Fallback Image

A more user-friendly approach is to replace the broken image with a default or fallback image.

HTML:

<img id="userAvatar" src="path/to/user/avatar.jpg" alt="User Avatar">

JavaScript:

const userAvatar = document.getElementById('userAvatar');
const fallbackAvatar = 'images/default-avatar.png';

userAvatar.addEventListener('error', function handleError() {
console.log('User avatar failed to load. Setting fallback.');

// Set the src to the fallback image
userAvatar.src = fallbackAvatar;
});
warning

Critical Warning: You must ensure that your fallbackAvatar image path is valid and accessible. If the fallback image also fails to load, it will trigger the error event again, causing an infinite loop that can crash the browser.

Conclusion

Handling missing and broken images requires two distinct approaches that are simple to implement.

  • To check if an <img> element has an empty or missing src attribute, the most reliable method is to check the "falsiness" of its attribute value: if (!element.getAttribute('src')).
  • To check if an image src is invalid (a broken link), you must listen for the error event on the element and then take action, such as hiding the image or providing a fallback src.

By implementing these checks, you can create a more robust and professional user experience, free of broken image icons.