How to get only direct child elements by jQuery function

Jason Li picture Jason Li · Sep 10, 2010 · Viewed 76.4k times · Source

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 <tbody> 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.

Answer

Josh Leitzel picture Josh Leitzel · Sep 10, 2010

You can use find():

tbl.find("> tbody > tr")