Replacing empty <img> src attributes using JavaScript.
Tags: javascript, tutorial, codenewbie, hack
Published: 2020-06-20 14:37:50

If you find yourself in the middle of a project where some of the images for your website are not available to you yet, this article may help you find and replace those empty `src` attributes with a default image of your choosing. Beware, this is a vanilla JavaScript solution and I assume here that you have at least some basic understanding of this programming language. 

I stumbled upon this problem recently while working on a portfolio-like webpage. I had the summary for all the projects showcased, but I was still working on some projects and so did not have an image available for them yet. Ideally, you should never leave the `src` attribute empty, but I did not want to solve this manually. 

I thought that simply checking each `img.src` and replacing the empty strings with a pre-selected image would solve my problem, but it did not. Why not? To debug this code I ran the `console.log` below and explored the results in my browser’s console, where I noticed something peculiar. 

```javascript
const images = document.querySelectorAll('img');
console.log(images[0].src);
```

It turns out that instead of an empty string I was getting back the URL of my webpage. Odd. After some research, I found out that this is due to most browsers’ behavior to an empty `src` attribute, which ends up making a new request to the original page, resulting in the original page’s URL instead of the expected empty string. 

After reviewing the `console.log(images)` resulting NodeList I decided to solve this problem by accessing the image attribute using the `img.getAttribute(‘src’)` method rather than using `img.src`. When I ran the code below it resulted in an empty string, which is what I wanted.

```javascript
console.log(images[0].getAttribute('src'));
```

Having accessed this I went on to write a function that checked the `src` attribute of my image. The logic of the `if` statement inside the function goes as follows: if the `src` attribute is empty, set the `image.src` path to a default image. If the `src` attribute is not empty we don't want anything to change so there is no need to add an `else` statement. 

In this case, I selected an image from inside my `images` folder, but you can use a service like [postimages.org](https://postimages.org/) to get a permanent link to your image and place that URL in the function instead (like `image.scr = ‘https://i.postimg.cc/AbCD1e23/coming-soon.png’`). 

```javascript
function replaceEmptySrc(image) {
   if (image.getAttribute('src') === '') {
      image.src = 'images/coming-soon.jpg';
   }
}
```

At one point I had about fifteen `src` attributes that were empty strings. Since I wanted a solution that would look into all of the images on the website checking for empty `src` attributes, I used the `forEach` method on the `images` NodeList and ran the previous function in it. Below you can find the complete solution.

__ES6+ Solution__:

```javascript
const images = document.querySelectorAll('img');
 
images.forEach(replaceEmptySrc);
 
function replaceEmptySrc(image) {
   if (image.getAttribute('src') === '') {
      image.src = 'images/coming-soon.jpg';
   }
}
```

__Shorter Solution__ (using the same logic):

```javascript
const images = document.querySelectorAll('img');
 
images.forEach((image) => {
   if (image.getAttribute('src') === '') image.src = 'images/coming-soon.jpg';
});
```

Now, if you try to open the webpage on an IE browser you will notice that the `alt` attribute is being displayed instead of the replacement image. This is because the `forEach` method is not supported on IE browsers (you can check this on [caniuse.com](https://caniuse.com/#search=forEach)). When an image, for some reason, cannot be displayed the browser will display the alternate text in its place. To correct this, change the `forEach` method to a `for loop`.

__IE Supported Solution__:

```javascript
const images = document.querySelectorAll('img');
 
function replaceEmptySrc() {
   for (let i = 0; i < images.length; i += 1) {
      if (images[i].getAttribute('src') === '') {
         images[i].src = 'images/coming-soon.jpg';
      }
   }
}
 
replaceEmptySrc();
```

Of course, there is more than one way to write this code and there are other solutions to this problem (with or without using JavaScript), but this is what worked for my project. I’d love for you to share your ideas and let me know what you think of my solution. 


------
Free resources related to images: 

* [developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img): Technical information on the HTML <img> element.
* [pexels.com](https://www.pexels.com/) || [pixabay.com](https://pixabay.com/): For free stock photos.
* [tinypng.com](https://tinypng.com/): To reduce the file size of your images.
* [postimages.org](https://postimages.org/): To generate permanent links to your images.