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>
<div id=”test1”>

function makeHR() will place the new horizontal rule

below this line

</div>

Even though we've appended the new <hr> to another object, the variable we assigned it to when we created it, var newHR, can still be used to manipulate the object (as long as the variable is declared outside the function). For example, let's append it to the end of the document so that it becomes the last object in the page. You might want to check that it's not there first. All we need to accomplish this is the following code:

The variable only refers to the last object created. That means if you click makeHR() again it will leave the <hr> at the bottom of the page and the new <hr> in div id="test1" is now var newHR. Click document.body.appendChild(newHR) again and you'll find 2 <hr>s at the bottom of the page.

 

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

<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