AppendChild after ID

Discussion in 'JavaScript' started by Echilon, Apr 6, 2007.

  1. #1
    I have a div containing a few elements. Is it possible to append a child after an element with a certain ID?
    Eg:
    <div id="container>
    <div id="child1"></div>
    <div id="child2"></div>
    </div>

    Could I append a child after child1, to give:
    <div id="container>
    <div id="child1"></div>
    <div id="child1a"></div>
    <div id="child2"></div>
    </div>
     
    Echilon, Apr 6, 2007 IP
  2. serjio28

    serjio28 Peon

    Messages:
    37
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Yes you could :)
    var div = document.getElementById('child1');
    var ndiv = document.createElement('DIV');
    if(ndiv && div){
     ndiv.innerHTML='child1a';
     ndiv.setAttribute('id','child1a');
     div.appendChild(ndiv);
    };
    
    Code (markup):
     
    serjio28, Apr 6, 2007 IP
  3. bibel

    bibel Active Member

    Messages:
    289
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    58
    #3
    Wrong !

    You need to use appendChild on "container", and then use the childNodes array to position the new div.

    I'm not sure it would work, though.
     
    bibel, Apr 6, 2007 IP
  4. serjio28

    serjio28 Peon

    Messages:
    37
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Which browser and OS you used when you got wrong results?
    I have tested my code under Mozilla 1.7.8 & Firefox 2.0.0.3 under Linux Debian 3.1
    It worked fine for me.
    Here the file that I used for the test:

    <html>
    <head>
    </head>
    <body>
    <div id="container">
        container
      <div id="child1">child1</div>
      <div id="child2">child2</div>
    </div>
    
    <script type="text/javascript" language="javascript">
    <!--
    
        var div = document.getElementById('child1');
        var ndiv = document.createElement('DIV');
        if(ndiv && div){
            ndiv.innerHTML='child1a';
            ndiv.setAttribute('id','child1a');
            div.appendChild(ndiv);
        };
    -->
    </script>
    
    </body>
    </html>
    
    Code (markup):
    Really I don't see any issues to refer to child DIV rather then "container" one. In DHTML we can to refer by ID to any element of the page.
     
    serjio28, Apr 6, 2007 IP
  5. Echilon

    Echilon Peon

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks Serjio, works perfectly :)

    
    child1 = document.getElementById('child1');
    child1a = document.createElement('div');
    child1a.id='child1a';
    child1.parentNode.insertBefore(child1a,child1.nextSibling);
    
    Code (markup):
     
    Echilon, Apr 6, 2007 IP