Ajaxorized

Magic domwalking

June 11, 2008

Prototype contains a number of functions that can be very useful in walking trough your DOM structure. Let's look at a short example. Suppose we have this piece of HTML:

 
<table id = "maintable">
<tbody>
<tr class = "row" id = "row1">
<td class = "cell" id = "cell1">Cell 1</td>
<td class = "cell" id = "cell2">Cell 2</td>
<td class = "cell" id = "cell3">Cell 3</td>
</tr>
<tr class = "row" id = "row2">
<td class = "cell" id = "cell4" colspan = "3">
<select id = "selectbox">
					<optgroup id = "group1">First group</optgroup>
					<option value = "1" id = "option1">Option 1</option>
					<option value = "2" id = "option2">Option 2</option>
					<optgroup id = "group2">Second group</optgroup>
					<option value = "3" id = "option3">Option 3</option>
					<option value = "4" id = "option4">Option 4</option>
				</select>
</td>
</tr>
</tbody>
</table>
 

Using up(), down(), next() and previous() we can find our way easily trough the DOM elements:

 
$('maintable').down(); // returns tbody element
$('maintable').down(1); // returns tr#row1
$('maintable').down().down().down(); // returns td#cell1, use down(2) instead
$('maintable').down(2).next(); // returns td#cell2
$('cell1').up(2); // returns table#maintable
$('cell2').up().next().down(1); // returns select#selectbox
 
/* include some CSS Selectors */
$$('table')[0].down(1); // returns tr#row1, use $('maintable') instead
$('maintable').down('.row'); // return tr#row1
$('maintable').down('#group1'); // returns optgroup#group1
$('option2').next('option'); // returns option#option3, mind skipping of optgroup
$('option4').up('.row').previous('.row').down('.cell'); // return td#cell1
Add to: del.icio.us Reddit Slashdot Digg Facebook Technorati Google StumbleUpon Windows Live Yahoo
topFiled under: Prototype, Javascript | Willem @ 9:52 am | Comments (1)