1

I have the following code for viewing an image in a new window. Both code snippets are able to produce the same HTML in the new window but the first one is not rendering the image and the second one is working fine.

<a onclick="window.open(this.href);return false;" href="javascript: var i = new Image(250, 250);i.src='image_url';   document.body.appendChild(i);" >VIEW1</a>

<a onclick="window.open(this.href);return false;" href="javascript: document.body.innerHTML='<img width=&quot;250&quot; height=&quot;250&quot; src=&quot;image_url&quot;/>';">VIEW2</a>

I want to know why innerHTML is working and appendChild not working

user4020527
  • 1
  • 8
  • 20
  • see the answer here on innerhtml vs appendChild and in particular: https://stackoverflow.com/questions/23338978/the-difference-between-innerhtml-and-appendchild and the answer https://stackoverflow.com/questions/2305654/innerhtml-vs-appendchildtxtnode where I think the key point is: The latter (appendChild) does not cause a complete rebuild of the DOM or even all of the elements/nodes within the target. The former (setting innerHTML) does cause a complete rebuild of the content of the target element, which if you're appending is unnecessary. – shelbypereira Jan 11 '18 at 07:46
  • But when i tried to execute the same javascript code using script tag i was able to see the image – deshmanth chennuri Jan 11 '18 at 08:04
  • You can use full path of image source – SM Chinna Feb 27 '18 at 06:28

1 Answers1

-1

The "URL" is for the link to the picture, and the "text" is there as a description if the Image should for some reason not load (broken requests)

  <a onclick="window.open(this.href);return false;" href="javascript: document.body.innerHTML='<div>&lt;Img width=&quot;250&quot; height=&quot;250&quot; src=&quot;file:///home/lt-176/tudip-image.jpg&quot; alt=&quot;text&quot;&gt;</div>';">VIEW2</a>

image src path to give full path...is working

SM Chinna
  • 341
  • 2
  • 7