Check if an img src is empty using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 6, 2022

banner

Photo from Unsplash

Check if an img src is empty using JavaScript #

Use the getAttribute() method to check if an image src is empty, e.g. img.getAttribute('src'). If the src attribute does not exist, the method returns either null or empty string, depending on the browser's implementation.

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" alt="banner" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const img = document.getElementById('img'); const src = img.getAttribute('src'); if (!src) { console.log('img src is empty'); } else { console.log('img src is NOT empty'); }

We used the getAttribute method to get the value of the src attribute of the image element.

If the provided attribute is not set on the element, the method returns a null or "" (empty string) value.

If the element's src attribute is not empty, the value of the attribute is returned, here is an example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <img id="img" src="http://bobbyhadz.com/images/blog/javascript-replace-all-child-nodes/banner.webp" alt="banner" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const img = document.getElementById('img'); const src = img.getAttribute('src'); console.log(src); // 👉️ "http://bobbyhadz.com/images/blog/javascript-replace-all-child-nodes/banner.webp" if (!src) { console.log('img src is empty'); } else { // 👇️ this runs console.log('img src is NOT empty'); }

If the src attribute is set on the image element, the else block runs.

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.