The Document Object Model (DOM)
Let's take a look at some of the methods and properties that help you access and manipulate this information, often called Walking The DOM.
Nodes
Suppose that our JavaScript object myxmlDoc contains the XML listing of the yacht race. The document element, <race>, contains two elements of type <yacht>; we say it has two children.
In general, you can get the number of children belonging to a particular element by using the childNodes.length property of the object. Because <race> is the document element, it is at the top of the object hierarchy, and we can refer to it simply with the variable myxmlDoc:
var noYachts = myxmlDoc.childNodes.length;
We can also determine information about individual children by appending the node number in parentheses:
myxmlDoc.childNode(0)
The preceding line refers to the first <yacht> element appearing in the document.
Caution
![]() | As in many programming constructs, the first element has the number zero, the second element has the number one, and so forth. |
We can test for the presence of children for a particular element by using the hasChildNodes() method:
myxmldoc.childNodes(1).hasChildNodes()
This line returns true because the second yacht in the document has three children (with tag names name, skipper, and helm). However,
myxmldoc.childNodes(1).childNodes(0).hasChildNodes()
returns false because the <name> element within that <yacht> element has no children.
Getting Tagnames
The tagname property allows you to find the tagname associated with a particular element:
myxmldoc.childNodes(0).childNodes(1).tagname
The preceding line returns skipper.
Getting Element Attributes
The method getAttribute("AttributeName") can be used to return the attribute values for a given element:
myxmldoc.childNodes(0).getAttribute("raceNo")
This line returns 74.
Tag Contents
The text property can be used to return the contents of a particular element. The line
myxmldoc.childNodes(0).childNodes(1).text
would return Walter Jeffries.
You'll learn about these and similar methods in more detail in Lesson 14, "Returning Data as XML."