Borislav Hadzhiev
Thu Jan 06 2022·2 min read
Photo by Jake Ingle
To clear an image src attribute:
setAttribute()
method to set the image's src
attribute to an
empty string.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" src="https://example.com/does-not-exist.jpg" alt="banner" /> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
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.
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
.
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.