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>
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):
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.
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.
Thanks Serjio, works perfectly child1 = document.getElementById('child1'); child1a = document.createElement('div'); child1a.id='child1a'; child1.parentNode.insertBefore(child1a,child1.nextSibling); Code (markup):