6

Do you know how to hide the classic “Image not found” or broken icon, but the alt still exist from a rendered HTML page when an image file is not found? Like this, <img id="testImg" src="#" alt="No Image"/> : enter image description here

change to: No Image (show the alt only)

Any working method using JavaScript/jQuery/CSS? Thank's

FanLee
  • 135
  • 4
  • 11
  • 4
    Possible duplicate of [How to silently hide "Image not found" icon when src source image is not found](https://stackoverflow.com/questions/3235913/how-to-silently-hide-image-not-found-icon-when-src-source-image-is-not-found) – mooga Apr 16 '18 at 02:17

3 Answers3

2

You can try this

  1. Create a text node element based on the alt text
  2. Insert the text node before the img
  3. Remove the img, or hide it if you want

function doSomething(elem){
  var alt = document.createTextNode( elem.getAttribute('alt') );
  
  elem.parentNode.insertBefore( alt, elem );
  
  elem.parentNode.removeChild( elem );
}
<img src="actual_image_src"  alt="helloworld" onerror="doSomething(this)" />
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24
-2

     $(function(){
          $('img').error(function(){
            $(this).css('opacity' ,0);
            $(this).next('.alt').text($(this).attr("alt"));
          });
      })
        .alt {
          opacity:0;
          float: left;
        }

        .alt:hover {
          opacity:1;
        }
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

            <img src="image_src"  alt="helloworld"  />
            <span class="alt"></span>
mooga
  • 3,136
  • 4
  • 23
  • 38
  • @FanLee, I have done it with `jQuery `, I hope it will help – mooga Apr 16 '18 at 02:41
  • @FanLee , you can see that answer https://stackoverflow.com/a/48006339/5940860 I think it's good idea as well to replace it with another background img – mooga Apr 16 '18 at 03:02
-3

You can fix this using the code below :

<img src="actual_image_src" onerror="this.src='on_error_image_src'"/>

Also you can use display:none css , if u dont want to show anything at all.

<img src="actual_image_src" onerror="this.style.display='none'"/>
Shifat
  • 732
  • 1
  • 6
  • 20