11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Figure 10-2: Simple tree walk output<br />

<strong>The</strong> problem with the previous example is that we knew the sibling and child relationships<br />

ahead of time by inspecting the markup in the example. How do you navigate a structure that<br />

you aren‘t sure of? We can avoid looking at nonexistent nodes by first querying the<br />

hasChildNodes() method for the current node before traversing any of its children. This<br />

method returns a Boolean value indicating whether or not there are children for the current<br />

node.<br />

if (current.hasChildNodes())<br />

current = current.firstChild;<br />

When traversing to a sibling or parent, we can simply use an if statement to query the property<br />

in question, for example,<br />

if (current.parentNode)<br />

current = current.parentNode;<br />

<strong>The</strong> following example demonstrates how to walk an arbitrary document. We provide a basic<br />

document to traverse, but you can substitute other documents as long as they are well formed:<br />

<br />

<br />

<br />

DOM Test<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!