append a child as the first node

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cleary1981
    New Member
    • Jun 2008
    • 178

    append a child as the first node

    Hi All,

    Im sure its possible, every time I create a new element and add it to a node it becomes the last child.
    a=appendChild(o bject);


    How do I append a child to be the first node?
  • mrhoo
    Contributor
    • Jun 2006
    • 428

    #2
    This code inserts a new p as the first child node of the first div in the document.
    Code:
    var who=document.createElement('p');
    var pa= document.getElementsByTagName('div')[0];
    
    if(pa.firstChild) pa.insertBefore(who,pa.firstChild);
    else pa.appendChild(who);

    Comment

    Working...