DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Replacing empty <img> src attributes using JavaScript.
Maria del Carmen Santiago
Maria del Carmen Santiago

Posted on • Updated on

Replacing empty <img> src attributes using JavaScript.

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.

const images = document.querySelectorAll('img');
console.log(images[0].src);
Enter fullscreen mode Exit fullscreen mode

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.

console.log(images[0].getAttribute('src'));
Enter fullscreen mode Exit fullscreen mode

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 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’).

function replaceEmptySrc(image) {
   if (image.getAttribute('src') === '') {
      image.src = 'images/coming-soon.jpg';
   }
}
Enter fullscreen mode Exit fullscreen mode

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:

const images = document.querySelectorAll('img');

images.forEach(replaceEmptySrc);

function replaceEmptySrc(image) {
   if (image.getAttribute('src') === '') {
      image.src = 'images/coming-soon.jpg';
   }
}
Enter fullscreen mode Exit fullscreen mode

Shorter Solution (using the same logic):

const images = document.querySelectorAll('img');

images.forEach((image) => {
   if (image.getAttribute('src') === '') image.src = 'images/coming-soon.jpg';
});
Enter fullscreen mode Exit fullscreen mode

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). 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:

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();
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (0)

Does your company have something to share with DEV?

Create an Organization and start sharing content with the community on DEV.