Working with The Document Object Model � II

Most Web programmers are familiar with Dynamic HTML (DHTML) and the underlying Document Object Models developed by Netscape and Microsoft for their respective browsers. However, there is a unifying Document Object Model (DOM) developed by the W3C that is less well known and, hence, used less often. The W3C DOM has several advantages over the DHTML DOM — using its node structure it is possible to easily navigate and change documents despite the user agent used to display them.

The previous article in this series introduced the W3C DOM and the JavaScript properties and methods that can be used to work with it. This article shows you how to find and recognize particular nodes when using JavaScript to transverse the DOM.

The W3C DOM is much more complex than shown within this article. There are several additional methods and properties at your disposal to use in manipulating documents. Further reading and information on the standard can be found on the W3C Web site at http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/Overview.html. Chapter 22 "JavaScript Objects and Dynamic HTML" of the book Web Standards Programmer's Reference: HTML, CSS, JavaScript, Perl, Python, and PHP also covers the details of the DHTML DOM.

A Sample Document

The code in this article uses the same example document as the previous article, duplicated here for your convenience. The following code shows the example document that renders as shown in Figure 1 and whose resulting DOM is shown in the illustration of Figure 2.

<html>
<head>
<title>Sample DOM Document</title>
   <style type="text/css">  
   div.div1 { background-color: #999999; }
   div.div2 { background-color: #BBBBBB; }
   table, table * { border: thin solid black; }
   table { border-collapse: collapse; }
   td { padding: 5px; }</style>
   <script type="text/JavaScript"></script></head>
<body>
<div class="div1">
   <h1>Heading 1</h1>
   <table>
      <tr><td>Cell 1</td><td>Cell 2</td></tr>
      <tr><td>Cell 3</td><td>Cell 4</td></tr>
   </table>
   <p>Lorem ipsum dolor sit amet, consectetuer adipiscing
   elit, sed diam <b>nonummy nibh euismod</b> tincidunt ut laoreet
   dolore magna aliquam erat volutpat. Ut wisi enim ad minim
   veniam, quis nostrud exerci tation ullamcorper suscipit
   lobortis nisl ut aliquip ex ea commodo consequat.</p>
</div>
<div class="div2">
   <h1>Heading 2</h1>
   <p>Lorem ipsum dolor sit amet, consectetuer adipiscing
   elit, sed diam nonummy nibh euismod tincidunt ut laoreet
   dolore magna aliquam erat volutpat. Ut wisi enim ad minim
   veniam, quis nostrud exerci tation ullamcorper suscipit
   lobortis nisl ut aliquip ex ea commodo consequat.</p>
   <ol id="sortme">An ordered list
      <li>Gamma</li>
      <li>Alpha</li>
      <li>Beta</li>
   </ol>
</div>
</body>
</html>

Figure 1

Figure 2

Working with The Document Object Model � II

Finding a Particular Node

The previous article showed you how to transverse the DOM using JavaScript — the first step in being able to work with and manipulate the document. The following example shows you how to use JavaScript to identify individual nodes in the document.

Example: Finding a Particular Node

This example expands upon the previous example by searching for a node with a particular ID in the DOM.

Source

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>DOM Find Node</title>
   <style type="text/css">
   div.div1 { background-color: #999999; }
   div.div2 { background-color: #BBBBBB; }
   table, table * { border: thin solid black; }
   table { border-collapse: collapse; }
   td { padding: 5px; }</style>
   <script type="text/JavaScript">
      function findNode(startnode,nodename,nodeid) {
         var foundNode = false;
         if ( startnode.nodeName == nodename &&
      startnode.id == nodeid ) {
   foundNode = startnode;
   } else {
      look_thru_children:
      if ( startnode.hasChildNodes() ) {
         var children = startnode.childNodes;
         for (var i = 0; i < children.length; i++) {
            foundNode = findNode(children[i],nodename,nodeid);
               if (foundNode) { break look_thru_children; }
         }
      }
   }
   return foundNode;
}function dofind() {
   alert("Click OK to find 'sortme' node");
   var node = findNode(document,"OL","sortme");
   alert("Found node: " + node.nodeName);
}</script></head>
<body onload="dofind()">
<div class="div1">
   <h1>Heading 1</h1>
   <table>
      <tr><td>Cell 1</td><td>Cell 2</td></tr>
      <tr><td>Cell 3</td><td>Cell 4</td></tr>
   </table>
   <p>Lorem ipsum dolor sit amet, consectetuer adipiscing
   elit, sed diam <b>nonummy nibh euismod</b> tincidunt ut laoreet
   dolore magna aliquam erat volutpat. Ut wisi enim ad minim
   veniam, quis nostrud exerci tation ullamcorper suscipit
   lobortis nisl ut aliquip ex ea commodo consequat.</p>
</div>
<div class="div2">
   <h1>Heading 2</h1>
   <p>Lorem ipsum dolor sit amet, consectetuer adipiscing
   elit, sed diam nonummy nibh euismod tincidunt ut laoreet
   dolore magna aliquam erat volutpat. Ut wisi enim ad minim
   veniam, quis nostrud exerci tation ullamcorper suscipit
   lobortis nisl ut aliquip ex ea commodo consequat.</p>
   <ol id="sortme">An ordered list
      <li>Gamma</li>
      <li>Alpha</li>
      <li>Beta</li>
   </ol>
</div>
</body>
</html>

This script works by traversing the DOM (using the same mechanisms from the previous example) looking for a node with the specified name (nodeName) and ID (id). When found, the search stops and the node is reported as found along with the type of node (element name). In this example OL is returned because the node with the ID sortme is an OL element.

The DOM provides another, easier mechanism to find an element with a particular id, namely the getElementById() method of the document object. In fact, the entire search function in the preceding script can be replaced with one line:

node = document.getElementById("sortme");

The previous method of traversing the DOM was used to illustrate how you can manually search the DOM. Manually traversing the DOM is useful when you need to know the context of a particular node — what elements are around the node in question.

Output

This script simply outputs the alert box shown in Figure 3. However, after execution the variable node contains a reference to the node being sought and can be manipulated, as shown in the next article.

[dompart2figure3.jpg]

Figure 3

Next Time

The first two articles in this series (which includes this article) have shown you how to effectively traverse a document's nodes using the DOM and how to recognize particular nodes. The next, and final, article in the series shows you how to manipulate the nodes.

This article is adapted from Web Standards Programmer's Reference: HTML, CSS, JavaScript, Perl, Python, and PHP by Steven M. Schafer (Wrox, 2005, ISBN: 0-7645-8820-6), from Chapter 21 "The Document Object Model." This is the second of a three-part series of articles on this topic which began with this part 1.

Reprinted with permission from the publisher.



About the Author

Steven M. Schafer

Steven Schafer programs in several languages and technologies, with extensive experience in Linux and related open-source platforms. He is the author of Web Standards Programmer's Reference: HTML, CSS, JavaScript, Perl, Python, and PHP (Wrox, 2005, ISBN: 0-7645-8820-6) as well as several other books and articles.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

  • Stories about devastating cyberattacks are plaguing the news. Why? The DNS protocol is easy to exploit. See your network the way hackers do—as an easy target. Learn how you can effectively secure your DNS infrastructure today.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds