Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set image via innerHTML [duplicate]

Confusing question...

In echo i have blank page.. if i set innerHTML="some text"; - it works. Why it's not working with image? If i directly goes to https://domain.com/adv/banner.jpg it will open image...

echo'
  <div id="yabanner"></div>

  <script>
  yaGetBanner();
  function yaGetBanner()
  {
    var el = document.getElementById("yabanner");
    el.innerHTML="<img src=\'https://domain.com/adv/banner.jpg\' width=\'400px\' height=\'150px\'>";
  }
  </script>
  ';
like image 591
WhoIsDT Avatar asked Apr 26 '16 08:04

WhoIsDT


People also ask

Does innerHTML work for images?

Image doesn't display inside innerHTML.

How do I change innerHTML content?

To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.

Is setting innerHTML synchronous?

Setting innerHTML is synchronous, as are most changes you can make to the DOM.


1 Answers

You need double quotes for the img attribute too, and then you need the backslashes. So your code would look like:

echo '
<div id="yabanner"></div>

<script>
yaGetBanner();
function yaGetBanner()
{
   var el = document.getElementById("yabanner");
   el.innerHTML="<img src=\"http://placehold.it/350x350\" width=\"400px\" height=\"150px\">";
}
</script>';

Also note that you have banner and adv in the name of your image URL. Adblockers will block these images or add inline styling to your img attributes containing that image.

I hope this help!

like image 188
node_modules Avatar answered Oct 01 '22 13:10

node_modules