Climbing the Node Tree - Easy Access to Document Elements Via the DOM
for IE5+ and Netscape 6
This example extracts the values from the cells in a table row and places the values into text inputs by clicking on a single link. All we need to do this is to know our starting point. In this case we're using ids assigned to the links and the document.getElementById() method. Then, using the DOM, we can access all the data in the row without the need for any other ids using a combination of parentNode, childNodes[i], and nodeValue.
| District | Street | Zip | Phone |
|---|---|---|---|
| 1st Police District | 24th and Wolf Streets | 19145 | (215) 686-3010 |
| 2nd Police District | Harbison Avenue and Levick Street | 19149 | (215) 686-3150 |
| 3rd Police District | 11th and Wharton Streets | 19147 | (215) 686-3030 |
| 4th Police District | 11th and Wharton Streets | 19147 | (215) 686-3040 |
| 5th Police District | Ridge Avenue and Cinnaminson Street | 19128 | (215) 686-3050 |
| 6th Police District | 11th and Winter Streets | 19107 | (215) 686-3060 |
<form name="pd">
<table border="0">
<tr>
<td>District<br>
<input name="DISTRICT" value="" size="20">
</td>
<td>Street<br>
<input name="STREET" value="" size="30">
</td>
<td>Zip<br>
<input name="ZIP" value="" size="7">
</td>
<td>Phone<br>
<input name="PHONE" value="" size="15">
</td>
</tr>
</table>
</form>
<table border="1" cellpadding="2" cellspacing="0">
<tr>
<th>District</th>
<th>Street</th>
<th>Zip</th>
<th>Phone</th>
</tr>
<tr>
<td><a href="javascript:getRow('ra')" id="ra">1st Police District</a></td>
<td>24th and Wolf Streets</td>
<td>19145</td>
<td>(215) 686-3010</td>
</tr>
</table>
<script>
function getRow(r){
var td0=document.getElementById(r); // - get the element (node) containing the id: the A tag, which is also a node
var td1=td0.childNodes[0].nodeValue; // - the text between the A tags
var td2=td0.parentNode.parentNode.childNodes[1].childNodes[0].nodeValue; // - tags (nodes) in this order: A, td[0], tr, td[1], text node[0], text
var td3=td0.parentNode.parentNode.childNodes[2].childNodes[0].nodeValue;
var td4=td0.parentNode.parentNode.childNodes[3].childNodes[0].nodeValue;
var f=document.pd;
f.DISTRICT.value=td1;
f.STREET.value=td2;
f.ZIP.value=td3;
f.PHONE.value=td4;
}
</script>
*WARNING!
Some versions of Netscape 6 (ie. the Mac version) treat whitespace as text nodes. Over at Bugzilla they're debating whether or not this should be regarded as a bug. As far as I'm concerned the answer is an emphatic YES!
In the table above, each <tr> has 4 childNodes (<td>s). But Netscape 6, because it was counting whitespace, kept insisting that there were 9 childNodes.
In order for this example to work properly in N6 I had to remove ALL the whitespace in the table rows. Do a 'View Source' to see what I mean. Then head over to Bugzilla and tell them that whitespace is not a text node.
PXL8 2003