21.4. Traversing a Document's Nodes
Using the JavaScript bindings, it is fairly trivial to navigate through a document's nodes, as demonstrated in the examples that follow.
Example: Navigating and Reporting a Document's Object ModelThis example navigates through a document's nodes and returns the document's DOM. Source This example uses the document example from earlier in the chapter with scripting necessary to navigate the DOM: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>DOM Walk and Display</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"> var s = new String(); // Add node's children to the listing (String s) function showChildren(node,lvl) { // Only track elements (1), text (3), and the document (9) if ( node.nodeType == 1 || node.nodeType == 3 || node.nodeType == 9 ) { // Add dashes to represent node level for (var x = 0; x < lvl; x++) { s = s + "--"; } // Report first 20 chars for text nodes if ( node.nodeType == 3 ) { mynodeType = node.nodeValue; if (mynodeType.length > 20) { mynodeType = mynodeType.slice(0,16) + "..."; } } else { // Report "Element/Tag" for elements mynodeType = "Element/Tag"; } s = s + "+ " + node.nodeName + " (" + mynodeType + ")\n"; // If the node has children, ... |
Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.