Check if an img src is empty using JavaScript

avatar

Borislav Hadzhiev

Thu Jan 06 20221 min read

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.