How to input a default image in case the src attribute of an HTML is not valid with JavaScript?

Spread the love

Sometimes, we want to input a default image in case the src attribute of an HTML is not valid with JavaScript.

In this article, we’ll look at how to input a default image in case the src attribute of an HTML is not valid with JavaScript.

How to input a default image in case the src attribute of an HTML is not valid with JavaScript?

To input a default image in case the src attribute of an HTML is not valid with JavaScript, we set the onerror property to a function that sets the src property of the img element to a default URL.

For instance, we write

const img = document.getElementById("imageId");
img.onerror = () => {
  img.src = "../error.png";
};
img.src = "../correct.webp.png";

to select the img element with getElementById.

Then we set img.onerror to a function that sets the src property to the default image when the actual image doesn’t load.

And we set the src to the actual image’s URL with

img.src = "../correct.webp.png";

Conclusion

To input a default image in case the src attribute of an HTML is not valid with JavaScript, we set the onerror property to a function that sets the src property of the img element to a default URL.

Leave a Reply

Your email address will not be published. Required fields are marked *