0

I wrote some jQuery to select the cells from a table with a certain class; in this case, "hello". However, the table has nested tables with a column of the same class. How do I select the cells from the outer table but not select the cells from the inner? See below:

HTML:
<table class="foo"> <!-- this is the outer table
  <tbody>
    <tr>
      <td class="hello"> <!-- select this cell

        <table> <!-- this is the nested table
          <tbody>
            <tr>
              <td class="hello"> <!-- do not select this cell
              </td>
            </tr>
          </tbody>
        </table>

      </td>
    </tr>
  </tbody>
</table>

jQuery:
// this selects the nested cells as well
$('table.foo:first').find('td.hello').doSomething();
3
  • Something like $('table:first tbody tr td.hello').doSomething(); Commented Jun 21, 2010 at 18:37
  • @Chad: This wouldn't work. It will select all descendant tbody s and therefore all td s. Commented Jun 21, 2010 at 18:40
  • @Felix Kling, Right, I should have had > between each element in the selector Commented Jun 21, 2010 at 19:12

2 Answers 2

5

What you want is to avoid recursing too deeply, so you can go like this:

$('table:first > tbody > tr > td.hello')

Which, I believe, is equivalent to

$('table:first').children('tbody').children('tr').children('td.hello')

Sign up to request clarification or add additional context in comments.

1 Comment

Whether your <tr>s are inside tbody or not, you have to use tbody selector.
0

If the classes on the outer table stay, you can just use:

$('table.foo > tbody > tr > td.hello');

One thing to note here perhaps is the fact that the <tbody> element is always present, even if you do not specify it explicitly. Due to the nature of the SGML/HTML/XHTML/whatyacallit definition for the <tbody> element, it has a optional opening tag. Even if the source does not contain it, the DOM element will be created when parsing the table.

1 Comment

I seem to remember there was some ambiguity about the autopresence of the tbody element in earlier versions of internet explorer. Does anybody happen to have a definitive reference about that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.