Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

10.3 Traversing and Modifying a DOM Tree

The DOM gives you access to the elements of a document, allowing you to modify the contents of a page dynamically using event-driven JavaScript. This section introduces properties and methods of all DOM nodes that enable you to traverse the DOM tree, modify nodes and create or delete content dynamically.

Figure 10.2 shows some of the functionality of DOM nodes, as well as two additional methods of the document object. The program allows you to highlight, modify, insert and remove elements.

 1    <?xml version = "1.0" encoding = "utf-8"?>
 2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 3       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5    <!-- Fig. 10.2: dom.html --> 
 6    <!-- Basic DOM functionality. --> 
 7    <html xmlns = "http://www.w3.org/1999/xhtml">
 8       <head>
 9          <title>Basic DOM Functionality</title>
10          <style type = "text/css">
11             h1, h3       { text-align: center;
12                            font-family: tahoma, geneva, sans-serif }
13             p            { margin-left: 5%;
14                            margin-right: 5%;
15                            font-family: arial, helvetica, sans-serif }
16             ul           { margin-left: 10% }
17             a            { text-decoration: none }
18             a:hover      { text-decoration: underline }
19             .nav         { width: 100%;
20                            border-top: 3px dashed blue;
21                            padding-top: 10px }
22             .highlighted { background-color: yellow }
23             .submit      { width: 120px }
24          </style>
25          <script type = "text/javascript">
26             <!--
27             var currentNode; // stores the currently highlighted node 
28             var idcount = 0; // used to assign a unique id to new elements 
29
30             // get and highlight an element by its id attribute 
31             function byId()
32             {

Fig. 10.2. Basic DOM functionality. (Part 1 of 8.)

33             var id = document.getElementById( "gbi" ).value;
34             var target = document.getElementById( id );
35
36             if ( target )
37                switchTo( target );
38          } // end function byId
39
40          // insert a paragraph element before the current element
41          // using the insertBefore method
42          function insert()
43          {
44             var newNode = createNewNode(
45                document.getElementById( "ins" ).value );
46             currentNode.parentNode.insertBefore( newNode, currentNode );
47             switchTo( newNode );
48          } // end function insert
49
50          // append a paragraph node as the child of the current node
51          function appendNode()
52          {
53             var newNode = createNewNode(
54                document.getElementById( "append" ).value );
55             currentNode.appendChild( newNode );
56             switchTo( newNode );
57          } // end function appendNode
58
59          // replace the currently selected node with a paragraph node
60          function replaceCurrent()
61          {
62             var newNode = createNewNode(
63                document.getElementById( "replace" ).value );
64             currentNode.parentNode.replaceChild( newNode, currentNode );
65             switchTo( newNode );
66          } // end function replaceCurrent
67
68          // remove the current node 
69          function remove()
70          {
71             if ( currentNode.parentNode == document.body )
72                alert( "Can't remove a top-level element." );
73             else
74             {
75                var oldNode = currentNode;
76                switchTo( oldNode.parentNode );
77                currentNode.removeChild( oldNode );
78             } // end else
79          } // end function remove
80
81          // get and highlight the parent of the current node 
82          function parent()
83          {
84             var target = currentNode.parentNode;
85

Fig. 10.2. Basic DOM functionality. (Part 2 of 8.)

86             if ( target != document.body )
87                switchTo( target );
88             else
89                alert( "No parent." );
90          } // end function parent
91
92          // helper function that returns a new paragraph node containing 
93          // a unique id and the given text 
94          function createNewNode( text )
95          {
96             var newNode = document.createElement( "p" );
97             nodeId = "new" + idcount;
98             ++idcount;
99             newNode.id = nodeId;
100            text = "[" + nodeId + "] " + text;
101            newNode.appendChild(document.createTextNode( text ) );
102            return newNode;
103         } // end function createNewNode
104
105         // helper function that switches to a new currentNode 
106         function switchTo( newNode )
107         {
108            currentNode.className = ""; // remove old highlighting
109            currentNode = newNode;
110            currentNode.className = "highlighted"; // highlight new node 
111            document.getElementById( "gbi" ).value = currentNode.id;
112         } // end function switchTo 
113         // -->
114      </script>
115   </head>
116   <body onload = "currentNode = document.getElementById( 'bigheading' )">
117      <h1 id = "bigheading" class = "highlighted">
118         [bigheading] DHTML Object Model</h1>
119      <h3 id = "smallheading">[smallheading] Element Functionality</h3>
120      <p id = "para1">[para1] The Document Object Model (DOM) allows for
121         quick, dynamic access to all elements in an XHTML document for
122         manipulation with JavaScript.</p>
123      <p id = "para2">[para2] For more information, check out the
124         "JavaScript and the DOM" section of Deitel's
125         <a id = "link" href = "http://www.deitel.com/javascript">
126            [link] JavaScript Resource Center.</a></p>
127      <p id = "para3">[para3] The buttons below demonstrate:(list)</p>
128      <ul id = "list">
129         <li id = "item1">[item1] getElementById and parentNode</li>
130         <li id = "item2">[item2] insertBefore and appendChild</li>
131         <li id = "item3">[item3] replaceChild and removeChild </li>
132      </ul>
133      <div id = "nav" class = "nav">
134         <form onsubmit = "return false" action = "">
135            <table>
136               <tr>
137                  <td><input type = "text" id = "gbi"
138                     value = "bigheading" /></td>

Fig. 10.2. Basic DOM functionality. (Part 3 of 8.)

139                     <td><input type = "submit" value = "Get By id"
140                        onclick = "byId()" class = "submit" /></td>
141                  </tr><tr>
142                     <td><input type = "text" id = "ins" /></td>
143                     <td><input type = "submit" value = "Insert Before"
144                        onclick = "insert()" class = "submit" /></td>
145                  </tr><tr>
146                     <td><input type = "text" id = "append" /></td>
147                     <td><input type = "submit" value = "Append Child"
148                        onclick = "appendNode()" class = "submit" /></td>
149                  </tr><tr>
150                     <td><input type = "text" id = "replace" /></td>
151                     <td><input type = "submit" value = "Replace Current"
152                        onclick = "replaceCurrent()" class = "submit" /></td>
153                  </tr><tr><td />
154                     <td><input type = "submit" value = "Remove Current"
155                        onclick = "remove()" class = "submit" /></td>
156                  </tr><tr><td />
157                     <td><input type = "submit" value = "Get Parent"
158                        onclick = "parent()" class = "submit" /></td>
159                  </tr>
160               </table>
161            </form>
162         </div>
163      </body>
164   </html>

10-04a_01.jpg

a) This is the page when it first loads. It begins with the large heading highlighted.

Fig. 10.2. Basic DOM functionality. (Part 4 of 8.)

10-05b_02.jpg

b) This is the document after using the Get By id button to select para3.

10-06c_03.jpg

c) This is the document after inserting a new paragraph before the selected one.

Fig. 10.2. Basic DOM functionality. (Part 5 of 8.)

10-07d_04.jpg

d) Using the Append Child button, a child paragraph is created.

10-08e_05.jpg

e) The selected paragraph is replaced with a new one.

Fig. 10.2. Basic DOM functionality. (Part 6 of 8.)

10-09f_06.jpg

f) The Get Parent button gets the parent of the selected node.

10-10g_07.jpg

g) Now we select the first list item.

Fig. 10.2. Basic DOM functionality. (Part 7 of 8.)

10-11h_08.jpg

h) The Remove Current button removes the current node and selects its parent.

Fig. 10.2. Basic DOM functionality. (Part 8 of 8.)

Lines 117–132 contain basic XHTML elements and content. Each element has an id attribute, which is also displayed at the beginning of the element in square brackets. For example, the id of the h1 element in lines 117–118 is set to bigheading, and the heading text begins with [bigheading]. This allows the user to see the id of each element in the page. The body also contains an h3 heading, several p elements, and an unordered list.

A div element (lines 133–162) contains the remainder of the XHTML body. Line 134 begins a form element, assigning the empty string to the required action attribute (because we're not submitting to a server) and returning false to the onsubmit attribute. When a form's onsubmit handler returns false, the navigation to the address specified in the action attribute is aborted. This allows us to modify the page using JavaScript event handlers without reloading the original, unmodified XHTML.

A table (lines 135–160) contains the controls for modifying and manipulating the elements on the page. Each of the six buttons calls its own event-handling function to perform the action described by its value.

The JavaScript code begins by declaring two variables. The variable currentNode (line 27) keeps track of the currently highlighted node, because the functionality of the buttons depends on which node is currently selected. The body's onload attribute (line 116) initializes currentNode to the h1 element with id bigheading. Variable idcount (line 28) is used to assign a unique id to any new elements that are created. The remainder of the JavaScript code contains event handling functions for the XHTML buttons and two helper functions that are called by the event handlers. We now discuss each button and its corresponding event handler in detail.

Finding and Highlighting an Element Using getElementById and className

The first row of the table (lines 136-141) allows the user to enter the id of an element into the text field (lines 137–138) and click the Get By Id button (lines 139–140) to find and highlight the element, as shown in Fig. 10.2(b) and (g). The onclick attribute sets the button's event handler to function byId.

The byId function is defined in lines 31–38. Line 33 uses getElementById to assign the contents of the text field to variable id. Line 34 uses getElementById again to find the element whose id attribute matches the contents of variable id, and assign it to variable target. If an element is found with the given id, getElementById returns an object representing that element. If no element is found, getElementById returns null. Line 36 checks whether target is an object—recall that any object used as a boolean expression is true, while null is false. If target evaluates to true, line 37 calls the switchTo function with target as its argument.

The switchTo function, defined in lines 106–112, is used throughout the program to highlight a new element in the page. The current element is given a yellow background using the style class highlighted, defined in line 22. Line 108 sets the current node's className property to the empty string. The className property allows you to change an XHTML element's class attribute. In this case, we clear the class attribute in order to remove the highlighted class from the currentNode before we highlight the new one.

Line 109 assigns the newNode object (passed into the function as a parameter) to variable currentNode. Line 110 adds the highlighted style class to the new currentNode using the className property.

Finally, line 111 uses the id property to assign the current node's id to the input field's value property. Just as className allows access to an element's class attribute, the id property controls an element's id attribute. While this isn't necessary when switchTo is called by byId, we will see shortly that other functions call switchTo. This line makes sure that the text field's value is consistent with the currently selected node's id. Having found the new element, removed the highlighting from the old element, updated the currentNode variable and highlighted the new element, the program has finished selecting a new node by a user-entered id.

Creating and Inserting Elements Using insertBefore and appendChild

The next two table rows allow the user to create a new element and insert it before the current node or as a child of the current node. The second row (lines 141–145) allows the user to enter text into the text field and click the Insert Before button. The text is placed in a new paragraph element, which is then inserted into the document before the currently selected element, as in Fig. 10.2(c). The button in lines 143–144 calls the insert function, defined in lines 42–48.

Lines 44–45 call the function createNewNode, passing it the value of the input field (whose id is ins) as an argument. Function createNewNode, defined in lines 94–103, creates a paragraph node containing the text passed to it. Line 96 creates a p element using the document object's createElement method . The createElement method creates a new DOM node, taking the tag name as an argument. Note that while createElement creates an element, it does not insert the element on the page.

Line 97 creates a unique id for the new element by concatenating "new" and the value of idcount before incrementing idcount in line 98. Line 99 assigns the id to the new element. Line 100 concatenates the element's id in square brackets to the beginning of text (the parameter containing the paragraph's text).

Line 101 introduces two new methods. The document's createTextNode method creates a node that can contain only text. Given a string argument, createTextNode inserts the string into the text node. In line 101, we create a new text node containing the contents of variable text. This new node is then used (still in line 101) as the argument to the appendChild method, which is called on the paragraph node. Method appendChild is called on a parent node to insert a child node (passed as an argument) after any existing children.

After the p element is created, line 102 returns the node to the calling function insert, where it is assigned to variable newNode in lines 44–45. Line 46 inserts the newly created node before the currently selected node. The parentNode property of any DOM node contains the node's parent. In line 46, we use the parentNode property of current Node to get its parent.

We call the insertBefore method (line 46) on the parent with newNode and currentNode as its arguments to insert newNode as a child of the parent directly before currentNode. The general syntax of the insertBefore method is

  • parent.insertBefore( newChild, existingChild );

The method is called on a parent with the new child and an existing child as arguments. The node newChild is inserted as a child of parent directly before existingChild. Line 47 uses the switchTo function (discussed earlier in this section) to update the currentNode to the newly inserted node and highlight it in the XHTML page.

The third table row (lines 145–149) allows the user to append a new paragraph node as a child of the current element, demonstrated in Fig. 10.2(d). This feature uses a similar procedure to the insertBefore functionality. Lines 53–54 in function appendNode create a new node, line 55 inserts it as a child of the current node, and line 56 uses switchTo to update currentNode and highlight the new node.

Replacing and Removing Elements Using replaceChild and removeChild

The next two table rows (lines 149–156) allow the user to replace the current element with a new p element or simply remove the current element. Lines 150–152 contain a text field and a button that replaces the currently highlighted element with a new paragraph node containing the text in the text field. This feature is demonstrated in Fig. 10.2(e).

The button in lines 151–152 calls function replaceCurrent, defined in lines 60–66. Lines 62–63 call createNewNode, in the same way as in insert and appendNode, getting the text from the correct input field. Line 64 gets the parent of currentNode, then calls the replaceChild method on the parent. The replaceChild method works as follows:

  • parent.replaceChild( newChild, oldChild );

The parent's replaceChild method inserts newChild into its list of children in place of oldChild.

The Remove Current feature, shown in Fig. 10.2(h), removes the current element entirely and highlights the parent. No text field is required because a new element is not being created. The button in lines 154-155 calls the remove function, defined in lines 69– 79. If the node's parent is the body element, line 72 alerts an error—the program does not allow the entire body element to be selected. Otherwise, lines 75–77 remove the current element. Line 75 stores the old currentNode in variable oldNode. We do this to maintain a reference to the node to be removed after we've changed the value of currentNode. Line 76 calls switchTo to highlight the parent node.

Line 77 uses the removeChild method to remove the oldNode (a child of the new currentNode) from its place in the XHTML document. In general,

  • parent.removeChild( child );

looks in parent's list of children for child and removes it.

The final button (lines 157–158) selects and highlights the parent element of the currently highlighted element by calling the parent function, defined in lines 82–90. Function parent simply gets the parent node (line 84), makes sure it is not the body element, (line 86) and calls switchTo to highlight it (line 87). Line 89 alerts an error if the parent node is the body element. This feature is shown in Fig. 10.2(f).

This section introduced the basics of DOM tree traversal and manipulation. Next, we introduce the concept of collections, which give you access to multiple elements in a page.

  • + Share This
  • 🔖 Save To Your Account