views:

70

answers:

3

I have a table structure like this:

<table1>
  <tbody>
    <tr>
      <td></td>
        ...
      <td>
        <table2>
          <tbody>
            <tr>
              <td></td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
   </tbody>
  </table>

in javascript, I have a variable "tbl" with value of $(table1), and then I want to get all direct child elements(tr) of of table1. My code is :

$('tr', tb1)

Apparently it returns all tr elements in table1 and table2. I think I can get by

$('tr', tb1).not(function(){return $(this).parent().parent()[0] != tb1;})

or this kind of logic.

I know $('table1 > tbody > tr') can get the direct child tr. Unfortunately I can not use this.

Anyone has good idea about this?

Thanks.

+3  A: 

You can use find():

tbl.find("> tbody > tr")

Josh Leitzel
this is bralliant idea. $('> tbody > tr', tb1) also works for me. Thank you.
Jason Li
A: 

http://api.jquery.com/child-selector/

$('tb1 > tr')

Jeremy
This would only work if `tb1` were an HTML tag, which it is not; and if `tr` were a direct child of it (which it is not, it is a direct child of `<tbody>`).
Josh Leitzel
A: 

This is exactly the reason why one should be careful with nesting tables. I really hope that you use them for data and not page layout.

Another issue that will probably ruin your day is using CSS selectors on nested tables... you basically have the same issue - you are unable to select TR elements of the outer table without selecting those inside the inner table, too. (You cannot use the child selector because it is not implemented in IE6)

This should work:

$("#table1 > tbody > tr")

However, I recommend that you hardcode the TBODY element, since you should not rely on the browser to create it for you.

Šime Vidas
"However, I recommend that you hardcode the TBODY element, since you should not rely on the browser to create it for you." -- this is good point.
Jason Li