Team LiB
Previous Section Next Section

Deleting and Replacing Nodes

It is often convenient to be able to remove nodes from the tree. The Node object supports the removeChild(child) method that is used to delete a node specified by the reference child that it is passed. For example,

current.removeChild(current.lastChild);

would remove the last child of the node referenced by the variable current. Note that the removeChild() method returns the Node object that was removed.

var lostChild = current.removeChild(current.lastChild);

Besides deleting a Node, you can replace one using the method replaceChild(newChild, oldChild), where newChild is the node to replace oldChild with. Be careful when using replaceChild(), as it will destroy the contents of nodes that are replaced. The following example shows deletion and replacement in action:

 <<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>Delete and Replace Demo<</title>>
<<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />>
<<script type="text/javascript">>
<<!-- 
function doDelete() 
{
  var deletePoint = document.getElementById('toDelete');
  if (deletePoint.hasChildNodes())
   deletePoint.removeChild(deletePoint.lastChild);
}

function doReplace()
{
 var replace = document.getElementById('toReplace');
 if (replace)
  {
    var newNode = document.createElement("strong");
    var newText = document.createTextNode("strong element");
    newNode.appendChild(newText);
    replace.parentNode.replaceChild(newNode, replace);
  }
}
//-->>
<</script>>
<</head>>
<<body>>
<<div id="toDelete">>
 <<p>>This is a paragraph<</p>>
 <<p>>This is <<em>>another paragraph<</em>> to delete<</p>>
 <<p>>This is yet another paragraph<</p>>
<</div>>
<<p>>
This paragraph has an <<em id="toReplace">>em element<</em>> in it.
<</p>>
<<hr />>
<<form action="#" method="get">>
      <<input type="button" value="Delete" onclick="doDelete();" />>
      <<input type="button" value="Replace" onclick="doReplace();" />>
<</form>>
<</body>>
<</html>>

Because of the fact that Opera and Mozilla-based browsers include white space in their DOM tree, you may notice that you have to press the Delete button a few more times in the preceding example to effect the same change as you would in IE. Despite the DOM being standard, we see that a subtle difference in interpretation of the standard can have significant consequences.

Modifying Nodes

Elements really cannot be directly modified, although their attributes certainly can. This may seem strange, but it makes perfect sense when you consider that elements contain text nodes. To effect a change, you really have to modify the text nodes themselves. For example, if you had

<<p id="p1">>This is a test<</p>>

you would use

textNode = document.getElementById('p1').firstChild;

to access the text node “This is a test” within the paragraph element. Notice how we strung together the firstChild property with the method call. Experienced DOM programmers find that stringing methods and properties together like this helps avoid having to use numerous individual statements to access a particular item. Once the textNode has been retrieved we could access its length using its length property (which indicates the number of characters it contains), or even set its value using the data property.

alert(textNode.length);                    // would return 14
textNode.data = "I've been changed!";

DOM Level 1 also defines numerous methods to operate on text nodes. These are summarized in Table 10-5.

Table 10-5: Text Node Manipulation Methods

Method

Description

>appendData(string)

This method appends the passed string to the end of the text node.

>deleteData(offset, count)

Deletes count characters starting from the index specified by offset.

>insertData(offset, string)

Inserts the value in string starting at the character index specified in offset.

>replaceData(offset, count, string)

Replaces count characters of text in the node starting from offset with corresponding characters from the string argument.

>splitText(offset)

Splits the text node into two pieces at the index given in offset. Returns the right side of the split in a new text node and leaves the left side in the original.

>substringData(offset,count)

Returns a string corresponding to the substring starting at index offset and running for count characters.

The following example illustrates these methods in use:

<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>Text Node Modifications<</title>>
<<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />>
<</head>>
<<body>>
<<p id="p1">>This is a test<</p>>

<<script type="text/javascript">>
<<!--
  var textNode = document.getElementById('p1').firstChild;
//-->>
<</script>>

<<form action="#" method="get">>
  <<input type="button" value="show"  onclick="alert(textNode.data);" />>
  <<input type="button" value="length" onclick="alert(textNode.length);" />>
  <<input type="button" value="change" onclick="textNode.data = 'Now a new value!'"
 />>
  <<input type="button" value="append" onclick="textNode.appendData(' added to the
 end');" />>
  <<input type="button" value="insert" onclick="textNode.insertData(0,'added to the front
');" />>
  <<input type="button" value="delete" onclick="textNode.deleteData(0, 2);" />>
  <<input type="button" value="replace" onclick="textNode.replaceData(0,4,'Zap!');"
 />>
  <<input type="button" value="substring" 
         onclick="alert(textNode.substringData(2,2));" />>
  <<input type="button" value="split" 
         onclick="temp = textNode.splitText(5); alert('Text node ='+textNode.data+'\
nSplit Value = '+temp.data);" />>
<</form>>
<</body>>
<</html>>
Note 

After retrieving a text node data value, you could always use any of the String methods discussed in Chapter 7 to modify the value and then save it back to the node.

Last, note it is also possible to manipulate the value of Comment nodes with these properties and methods. However, given that comments do not influence document presentation, modification is usually not performed this way. You may be tempted to start thinking about modifying CSS properties wrapped within an (X)HTML comment mask using such a technique, but this is not advisable. We will see later in the chapter, in the section entitled “The DOM and CSS,” how the DOM Level 2 provides access to CSS properties.


Team LiB
Previous Section Next Section