Rough Guide To The DOM (part 1) - Navigating The Family Tree (
Page 3 of 8 )
In addition to the various childNodes[], the DOM also offers a number of
other objects/properties which can simplify navigation between document
elements.
firstChild - a reference to the first child node in the collection
lastChild - a reference to the last child node in the collection
parentNode - a reference to the node one level up in the tree
nextSibling - a reference to the next node in the current collection
previousSibling - a reference to the previous node in the current collection
And so, with reference to the example above, I could use any of the
alternative routes below to navigate to the <div> tag.
document.childNodes[0].childNodes[1].firstChild
document.childNodes[0].firstChild.nextSibling.firstChild
document.childNodes[0].childNodes[1].firstChild.firstChild.parentNode
Each child in the tree can be either an HTML tag or a "text node". This
brings up an important point - blank spaces and carriage returns between
the various tags can affect the document tree structure, creating text
nodes in the tree structure and causing much gnashing of teeth as you
adjust your code to the new tree.