How to hide image broken icon using with JavaScript?

Spread the love

Sometimes, we want to hide image broken icon using with JavaScript.

In this article, we’ll look at how to hide image broken icon using with JavaScript.

How to hide image broken icon using with JavaScript?

To hide image broken icon using with JavaScript, we set the onerror property.

For instance, we write

const img = document.querySelector("img");
img.onerror = () => {
  img.style.display = "none";
};

to select the img element with querySelector.

Then we set its onerror property to a function that hides the image when the image fails to load.

We hide the element by setting img.style.display to 'none‘.

Conclusion

To hide image broken icon using with JavaScript, we set the onerror property.

Leave a Reply

Your email address will not be published.