Last updated: Mar 5, 2024
Reading timeยท3 min
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.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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 an 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 does not affect 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 of your page as normal.
visibility
propertyHere is an example that sets the image's visibility
property to hidden
.
const img = document.getElementById('img'); // ๐๏ธ set image src attribute to an empty string img.setAttribute('src', ''); // ๐๏ธ or hide image 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.
You can also use the removeAttribute
method to clear the image's src
attribute.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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 an empty string img.removeAttribute('src'); // ๐๏ธ or hide image img.style.display = 'none';
The Element.removeAttribute() method removes the attribute with the specified name from the element.
If you don't want to move the elements on the page when hiding the image, use
the visibility
property instead.
const img = document.getElementById('img'); // ๐๏ธ set image src attribute to an empty string img.removeAttribute('src'); // ๐๏ธ or hide image img.style.visibility = 'hidden';
You can learn more about the related topics by checking out the following tutorials: