Adding img element to div with javascript

I am trying to add img to a placehere div using JavaScript, but I have no luck. Can someone give me a hand with my code?

 <html> <script type="text/javascript"> var elem = document.createElement("img"); elem.setAttribute("src", "images/hydrangeas.jpg"); elem.setAttribute("height", "768"); elem.setAttribute("width", "1024"); elem.setAttribute("alt", "Flower"); document.getElementById("placehere").appendChild("elem"); </script> <body> <div id="placehere"> </div> </body> </html> 
+47
javascript dom
Oct 18 '11 at 5:22
source share
3 answers
 document.getElementById("placehere").appendChild(elem); 

not

 document.getElementById("placehere").appendChild("elem"); 

and use below to set the source

 elem.src = 'images/hydrangeas.jpg'; 
+52
Oct 18 '11 at 5:25
source share

It should be:

 document.getElementById("placehere").appendChild(elem); 

And put your div in front of your javascript, because if you do not, javascript will be executed before the div exists. Or wait for it to load. So your code is as follows:

 <html> <body> <script type="text/javascript"> window.onload=function(){ var elem = document.createElement("img"); elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png"); elem.setAttribute("height", "768"); elem.setAttribute("width", "1024"); elem.setAttribute("alt", "Flower"); document.getElementById("placehere").appendChild(elem); } </script> <div id="placehere"> </div> </body> </html> 

To prove your point, see this one with onload and this one without onload . Launch the console and you will find an error message indicating that the div does not exist or cannot find the appendChild null method.

+14
Oct 18 2018-11-11T00:
source share
 function image() { //dynamically add an image and set its attribute var img=document.createElement("img"); img.src="p1.jpg" img.id="picture" var foo = document.getElementById("fooBar"); foo.appendChild(img); } <span id="fooBar">&nbsp;</span> 
+3
Mar 18 '13 at 7:23
source share



All Articles