Javascript – DOM appendChild example

Javascript DOM method appendChild can be used to append a child to existing DOM element. For example it can be used to append an Image, Template instance, etc. to an element. Here is an example which appends an image to an existing div.
javascript-dom-append-child

<div id="id1">
  <div>child1</div>
  <div>child2</div>
</div>
<script type="text/javascript">
window.addEventListener("load", addImage);
function addImage() {
  var img = new Image();
  img.src = "/img/elephant1_small.jpg";
  document.querySelector("#id1").appendChild(img);
}
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments