DOMIT! v 0.1 Tutorial
<<    index    >>
1    2    3    4    5    6    7    8     9    10    11    12    13    14    15   
16    17    18    19    20    21    22    23    24    25    26   
firstChild and nextSibling

Iterating through a childNodes array is not the only technique available for traversing DOM nodes. Another means of doing this is by using firstChild and nextSibling.

As is apparent from its name, firstChild is a reference to the first child node of a node -- in other words, childNodes[0].

nextSibling is a reference to the node immediately after the current node -- in other words, the nextSibling of childNodes[0] is childNodes[1].

With this in mind, it is possible to rewrite the childNodes loop from the previous example so that it uses firstChild and nextSibling.

if ($cdCollection->documentElement->hasChildNodes()) {
	$currentNode =& $cdCollection->documentElement->firstChild;
	$i = 0;
	
	while ($currentNode != null) {
		echo ("The id of child node $i is: " . 
			$currentNode->attributes["id"] . 
			"\n");
			
		$currentNode =& $currentNode->nextSibling;
		$i++;		
	}
}


The results are identical to the childNodes loop:

The id of child node 0 is: 0001
The id of child node 1 is: 0002
The id of child node 2 is: 0003


Documentation generated by ClassyDoc, using the DOMIT! and SAXY parsers.
Please visit Engage Interactive to download free copies.