Search code examples
jquerydomjquery-selectors

Select highest level td's in nested table structure with jQuery


I am trying to select the highest level of tds in a nested table structure like this (inside the first level tds there are more tables with more tds that shouldn't be selected

<table>
  <tr>
    <td>        <!-- this is what I want to select -->
      <table /> <!-- more td's inside that I don't want to select -->
    </td>
  </tr>
  <tr>
    <td>        <!-- this is what I want to select -->
      <table /> <!-- more td's inside that I don't want to select -->
    </td>
  </tr>
</table>

To select the desired tds would be easy: table > tr > td. However there might be tables with tbody tags:

<table>
  <tbody>
    <tr>
      <td>        <!-- this is what I want to select -->
        <table /> <!-- more td's inside that I don't want to select -->
      </td>
    </tr>
    <tr>
      <td>        <!-- this is what I want to select -->
        <table /> <!-- more td's inside that I don't want to select -->
      </td>
    </tr>
  </tbody>
</table>

That itself would be easy as well: table > tbody > tr > td.

How can I find an easy expression that doesn't rely on the > child selector and works universally?

Something like table tr > td (which obviously wouldn't work since it selects tds inside the nested table. Thanks!


Solution

  • As I expressed in my comment, I'm all in favor of table > tbody > tr > td, but as an alternative, you can use

    td:not(td td)
    

    This selects all td elements that are not descendants of a td element. But note that this will only work with jQuery, because you usually cannot use complex selectors with :not.

    Alternatively, use the .not method:

    $('td').not('td td')