Navigating the DOM Tree

Node objects have a number of properties and methods for navigating around the document tree. Once you have a reference to an element, you can walk along the document tree to find other nodes. Let's focus on a particular part of the document tree in our example. The relationship each node has with the bike node is shown in this figure.


Navigating the DOM tree
Navigating the DOM tree  
The childNodes property is a list of all the nodes that are children of the node concerned. The following example will return all the child nodes of the element with an id of sports: 


var sports = document.getElementById('sports');
<< undefined
sports.childNodes;
<< NodeList [ #text "
", <p.swim>, #text "

", <p#bike>, #text "
", <p>, #text "
" ]
  

Note that the childNodes property returns all the nodes that are children of an element. This will include any text nodes and since whitespace is treated as a text node, there will often be empty text nodes in this collection.
The children property only returns any element nodes that are children of that node, so will ignore any text nodes. Note that this is only supported in Internet Explorer from version 9 onwards: 


sports.children // this will only contain paragraph elements
<< HTMLCollection [ <p>, <p>, <p> ]

sports.children.length
<< 3
  

The firstChild property returns the first child of a node:


sports.firstChild
<< #text "
"
  

And the lastChild property returns the last child of a node:

sports.lastChild
<< #text "
"
  

Be careful when using these propertiesthe first or last child node can often be a text node, even if it’s just an empty string generated by some whitespace.
For example, you might expect the first child node of the sports element to be the swim element and the last child to be the run element, but it is in fact a text node, generated by the whitespace characters in between the <section> and <p> tags:
The parentNode property returns the parent node of an element. The following code returns the sports node because it is the parent of the bike node: 


bike.parentNode;
<< <section id="sports">
  

The nextSibling property returns the next adjacent node (that is, the same parent). It will return null if the node is the last child node of that parent:


bike.nextSibling;
<< #text "
"
  

The previousSibling property returns the previous adjacent node. It will return null if the node is the first child of that parent:


bike.previousSibling
<< #text "
"
  

Once again, these methods find the next and previous node, not element, so they will often return a blank text node as in the examples above.

Using these properties allows you to navigate around the whole of the document tree. 

0 Response to "Navigating the DOM Tree"

Post a Comment