tags:

views:

134

answers:

2

If you have a recursive structure, say, child tables located inside td cells of parent tables, how best to traverse/select a particular parent table? For example, what if you wanted to find the next table up, or the 2nd table up?

One way might be to put something like this in a loop:

//Get the next parent up.
$parentTable = $table.parent('td,th')
    .parent('tr')
    .parent('tbody')
    .parent('table');

But that seems ugly AND fragile.

Something like this looks scary and probably not predictable either:

$parentTable = $table.parents('table').eq(1);  // Get the 2nd parent table up.

Resolved

I verified that $table.parents('table').eq(N-1) does indeed give you the Nth parent. As for why I'm using tables for formatting, I'm not, at least, not this time. :) I'm actually displaying recursive data, allowing it to be folded on the client. jQuery has me doing things I would not have even considered before.

And BTW, using .parent('table') won't work in this case, because parent() will only select the immediate parent. Likewise with child(), it selects immediate children only. The analogue of parents() is find(). Parents() goes all the way up, and find() goes all the way down. Great stuff!

Update

1.3 has added a new traversal method, closest(), that could also be useful here. Closest('table') will traverse upwards until it finds the nearest ancestor table.

+2  A: 

It depends on how precise you need to be.

$pTable = $table.parent('table'); //get the immediate parent table
$pTable = $table.parent('table.someclass') //get the parent table w/class someclass
$pTable = $table.parents('table').eq(n) //get the #-1 parent table

This is precisely one of the reasons that tables should only be used for tabular-data, not layouts. You should be able to confidently traverse the DOM in your applications.

tj111
+2  A: 
$table.parents('table')

Is as predictable as you can get -- it will give you a reverse list of parent tables between the starting object and the body.

If you can't determine the structure of the nested tables beforehand, then traversing isn't going to work, and you'll need to select the objects based on another criteria.

Adam Lassek