Borislav Hadzhiev
Thu Jan 06 2022·1 min read
Photo by Ben Waardenburg
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.
<!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.
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.
<!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.
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.