Home Page -> DOM Tutorials -> Dynamic Text -> Modifying a Node

Modifying a Node

In order to modify the definition list in our vocabulary example, we will use these functions:

document.createTextNode("node contents");
document.replaceChild(new_node, old_node);

The createTextNode function will create a new text node with the contents that you specify.

The replaceChild function puts the new node that you specify in place of the old node. There are two important things to know about this function.

  1. The new node comes first, then the old node.
  2. You should always use this function rather than directly assigning the nodes yourself. As you saw on the previous page, there are a lot of links among nodes, and the replaceChild function makes sure that they are all properly maintained. For example, if you have <div id="myDiv">, and you want to replace its lastChild node by some different text, you should do it like this:
    var myDiv = document.getElementById("myDiv");
    var newNode = document.createTextNode("different text");
    document.replaceChild( newNode, myDiv.lastChild );
    
    Do not do this:
    var myDiv = document.getElementById("myDiv");
    var newNode = document.createTextNode("different text");
    myDiv.lastChild = newNode; /* NO! NO! NO! */
    

Armed with this information, we can now write the gloss() function.

  Review of Nodes  Index The gloss() function