appendChild()
for IE5+, Netscape 6+, Mozilla 1.1+, and Safari
If you've looked at any of the other tutorials on this site, you've probably seen at least one example of appendChild() used to add a new or cloned object to the document. But that's not the only way you can use it. appendChild() can also be used with existing objects already in the document.
appendChild() let's you insert a node into another node as it's last child node.
Using appendChild() with New Objects
This is the example used in the createElement() tutorial. We create a horizontal rule and put it into div id="test1", which already contains 2 lines of text, using destinationNode.appendChild(newNode).
<script> var newHR; function makeHR(){ newHR = document.createElement('hr'); document.getElementById('test1').appendChild(newHR); } </script>
function makeHR() will place the new horizontal rule
below this line
Using appendChild() with Existing Objects
In the example below, we're going to take the "News" row in table id="menu1" and append it to table id="menu2". All we need to do is identify the row to be moved and place it in destination using appendChild(). appendChild() removes it from the first table in order to place it in the second.
This is a bit buggy with Mac IE 5
| About |
| News |
| Help |
| Links |
| Exit |
| Home |
<script> function moveRow(){ // -- get table id="menu1", 1st tbody, 2nd row var m1 = document.getElementById('menu1').getElementsByTagName('tbody')[0].childNodes[1]; if (m1) // -- append it to the 1st tbody of table id="menu2" document.getElementById('menu2').getElementsByTagName('tbody')[0].appendChild(m1); } </script>
Cool, yes?
Click here to see how this behaviour can be used to create a scrolling table.
PXL8 2003