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.

 5    <!-- Fig. 10.2: dom.html --> 
 6    <!-- Basic DOM functionality. --> 
 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 
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 );
36             if ( target )
37                switchTo( target );
38          } // end function byId
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
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
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
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
81          // get and highlight the parent of the current node 
82          function parent()
83          {
84             var target = currentNode.parentNode;

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
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
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>


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.)


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


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

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


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


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

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


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


g) Now we select the first list item.

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


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







  • parent.insertBefore( newChild, existingChild );



Replacing and Removing Elements Using replaceChild and removeChild



  • parent.replaceChild( newChild, oldChild );

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



  • parent.removeChild( child );

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



  • + Share This
  • 🔖 Save To Your Account