Append Child or Prepend Child using Javascript

Share this Article :


You are in this page it means,  You are looking for a Handy  function(s)   by which  you wanted  to    Create a Element  Dynamically  using Javascript  and Append  or  Prepend  that  Element  to a Particular  Element.

We wont  Disappoint you.  Here is the Pure  Javascript  Version of th  AppendChild  or PrependChild   Functions in Javascript

Append Child

// Create The Element Dynamically. Here we are creating  Div   
   var ele=document.createElement("div");
   // Assume our Parent Element  ID is  container
   // So  function  goes like below 
   appendElement('container',ele)
 
   // ACTUAL  CODE 
   function appendElement(parentID,child)
    {
        parent=document.getElementById(parentID);
        parent.appendChild(child);
    }

Hmm It seems this is known to you.. But You might be looking out for Prepending If I am not wrong, So here it is

Prepend Child

 // Create The Element Dynamically. Here we are creating  Div   
   var ele=document.createElement("div");
   // Assume our Parent Element  ID is  container
   // So  function  goes like below 
   prependElement('container',ele)
 
   // ACTUAL  CODE 
   function prependElement(parentID,child)
    {
        parent=document.getElementById(parentID);
        parent.insertBefore(child,parent.childNodes[0]);
    }

Hope You liked IT, and I also Hope It will be useful to you and will work for you also :)

Written by adrevol

{adrevol has written 91 posts on ITTreats.com . See all posts by }


Leave a Reply