Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an img element to a div with javascript

Tags:

javascript

dom

I am trying to add an img to the placehere div using JavaScript, however I am having no luck. Can anyone 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> 
like image 656
Andrew De Forest Avatar asked Oct 18 '11 05:10

Andrew De Forest


People also ask

How do you insert an image in JavaScript?

Create Image Element in JavaScriptCreate an image element using the createElement() method on the document object. Then, set an image URL to its src attribute. Finally, add the image element to the DOM hierarchy by appending it to the body element.


1 Answers

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

not

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

and use the below to set the source

elem.src = 'images/hydrangeas.jpg'; 
like image 69
Ghyath Serhal Avatar answered Sep 24 '22 04:09

Ghyath Serhal