Clear Img src attribute using JavaScript

avatar

Borislav Hadzhiev

Thu Jan 06 20222 min read

banner

Photo by Jake Ingle

Clear Img src attribute using JavaScript #

To clear an image src attribute:

  1. Use the setAttribute() method to set the image's src attribute to an empty string.
  2. Alternatively, hide the image element.

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" src="https://example.com/does-not-exist.jpg" alt="banner" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const img = document.getElementById('img'); // ๐Ÿ‘‡๏ธ set image src attribute to empty string img.setAttribute('src', ''); // ๐Ÿ‘‡๏ธ or hide image img.style.display = 'none';

We used the setAttribute method to set the src attribute of the image element to an empty string.

However, if you do that the image is still displayed as being broken.

Alternatively, you can hide the image by setting its display property to none.

We used the display property to hide the image element, however you might need to use the visibility property, depending on your use case.

When an element's display property is set to none, the element is removed from the DOM and has no effect on the layout. The document is rendered as though the element does not exist.

On the other hand, when an element's visibility property is set to hidden, it still takes up space on the page, however the element is invisible (not drawn). It still affects the layout on your page as normal.

Here is an example that sets the image's visibility property to hidden.

index.js
const img = document.getElementById('img'); img.style.visibility = 'hidden';

When the image's visibility is set to hidden, it is invisible, however it still takes up space on the page.

If you set the image's display property to none, the element is removed from the DOM and other elements take its space.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee