Adding an img element to a div with javascript

It should be:

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

And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:

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);
}
<div id="placehere"></div>

To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.


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

not

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

and use the below to set the source

elem.src = 'images/hydrangeas.jpg';

Tags:

Javascript

Dom