How to hide the <img> tag icon when the image is not found?

Asked

Viewed 45 times

0

I made a button of upload which displays a preview of the selected image, but for this, the tag img has its attribute src empty. So this icon which is pointed with the arrow.

I’ve tried everything, I put the attributes title, alt and yet it keeps showing! So I had the idea to use but I didn’t succeed either!

The attributes alt and title were filled, so I came to the conclusion that it’s not because they’re empty..

<div class="image">
    <img src="" alt="" title="" />
</div>

With Javascript, I select the tag img and check if the attribute src is "null", if yes, sets the style display like "None," but it hasn’t worked yet!

const img = document.querySelector("img").src;

if (src == null) {
    img.style.display = "none";
}

Here’s the whole structure inside the body page

<div class="container">
   <div class="wrapper">

      <div class="image">
         <img src="" alt="" title="">
      </div>

      <div class="content">
         <div class="icon">
            <i class="fas fa-cloud-upload-alt"></i>
         </div>
         <div class="text">
            Nenhuma Imagem Selecionada
         </div>
      </div>
      <div id="cancel-btn">
         <i class="fas fa-times"></i>
      </div>
      <div class="file-name">
         File name here
      </div>
   </div>
   <button onclick="defaultBtnActive()" id="custom-btn">Selecione uma Imagem</button>
   <input id="default-btn" type="file" hidden>
</div>

How do I hide that icon when there is no image?

  • 1

    Your question is well structured but does not put source code in image format, it makes it difficult for those who will try to answer. See how you format source code in your question here https://answall.com/editing-help.

  • 1

    Sorry, I’ll rephrase the question

  • Use the attribute/event onerror of [tag:html], as follows:: <img src="" alt="" title="" onerror="this.style.display = 'none'" /> that will solve this detail!

  • but when I select the image it does not appear visually

  • 1

    It does not appear because when the site is loaded, the tag img has not src and the event onerror is invoked. When this happens, the style display tag receives the value none. When you change the image to receive the file the user uploaded, you apparently forget to change the display: none for display: block or another value that makes it visible. Test declare tag like this <img src="" alt="" onerror='this.style.display = "none"' onload='this.style.display = "block"'/> .

  • I tried, but the error still persists :)

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.