. Advertisement .
. Advertisement .
When you require dynamically loading images, we need to set the src attribute. The img src attribute is used to specify an image’s URL. And, at any time, the src property can be changed. To clear the image src attribute, you can use
- Hide Image in an exceptional case
Using setAttribute() Method
The main purpose of this method is to add or set an attribute an image or any particular element. In the case of an attribute already defined or existing, the
setAttribute() method set the attribute’s value. Checkout the example
First, take a look at the HTML as an example
Now, use it with the
const image = document.getElementById('img'); // set image src attribute to the empty string image.setAttribute('src', ''); // hide image image.style.display = 'none';
Here, in this code, the
setAttribute() method is used to set the image ‘src’ attribute to an empty string.
Using Hide Image Method
As Its name suggests, this method can be used to hide the image. The main reason to use the hide image process is the need for it when the image is still visible but as a broken one.
There are two properties; display property and visibility property.
The display property is used to hide the elements of the image. In the case of the display property set to ‘
none’, the element has no effect on the layout of the web page as it is removed from the DOM. It shows as if the element doesn’t even exist.
Check out the display property set to ‘
const image = document.getElementById('img'); image.style.display = none;
Just as discussed, the element has been removed with the display to none.
Visibility property when set to ‘
hidden’, it will still occupy space on your page, though the element remains invisible on the page. The layout will remain as normal on the page.
Let’s take a look at the visibility property set to ‘
const image = document.getElementById('img'); image.style.visibility = 'hidden';
with the ‘
hidden’, the image has been hidden but still takes the space.
If you need assistance, feel free to drop your comment below!