Home > Articles > Open Source > Ajax & JavaScript

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020