Determining Node Information


s += nodeName + ": " + nodeValue +   " (" + nodeType + ")\n"; 

As already mentioned in the previous phrase, it is possible to gather information about a node, which is extremely useful when working on arbitrary DOM data.

Whereas nodeName gives information about the name of the node (tag name or #text for text nodes), nodeValue is useful only for text nodes and returns the actual text in the node. The third category of information comes from the nodeType property, which gives information regarding the kind of node. Table 5.1 contains a list of all possible values for nodeType.

Table 5.1. Node Types

Node Type

Description

1

Tag

2

Attribute

3

Text (includes whitespace)

8

HTML comment

9

Document

10

DTD

11

Fragment


The following code then analyzes a simple DOM structure and outputs information regarding all child nodes. Figure 5.2 shows the output in the browser.

Retrieving Node Information (nodeinfo.html)

<script language="JavaScript"   type="text/javascript"> window.onload = function() {   var s = "";   with (document.getElementById("para")) {     for (var i=0; i<childNodes.length; i++) {       with (childNodes[i]) {         s += nodeName + ": " + nodeValue +              " (" + nodeType + ")\n";       }     }   }   window.alert(s); } </script> <p ><em>JavaScript</em> Phrasebook</p> 

Figure 5.2. Information about all child nodes.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net