views:

4524

answers:

5

Title pretty much says it all.
Given a table like

<table>
  <tr>
    <th>Header 1</td>
    <th>Header 2</td>
  </tr>
  <tr>
    <td>Datum 1</td>
    <td> Datum 2</td>
  </tr>
  <tr>
    <td>Datum 1</td>
    <td> Datum 2</td>
  </tr>
</table>

How to select the row which contains the th headers and no other?

A: 

Dunno if it's like Dojo CSS3 queries, but you could use the first-child pseudo class, if jQuery supports it:

tr th:first-child

or

tr th:nth-child(1)

See: http://www.456bereastreet.com/archive/200601/css_3_selectors_explained/

Chris KL
+4  A: 
jQuery("tr:has(th)")

will select every tr that contains at least one th

kthxbye :)

Vincent Robert
+2  A: 

Use the :has selector:

$('tr:has(th)').addClass('sample')

Probably won't work if you have a table with mixed th and td children though.

Rob
+10  A: 

Expression:

$(function() {
  $("tr:has(th):not(:has(td))").hide();
});

or even just:

$(function() {
  $("tr:not(:has(td))").hide();
});

Full example:

<html>
<head>
  <title>Layout</title>
</head>
<body>
<table>
  <tr>
    <th>Header 1</td>
    <th>Header 2</td>
  </tr>
  <tr>
    <td>Datum 1</td>
    <td> Datum 2</td>
  </tr>
  <tr>
    <td>Datum 1</td>
    <td> Datum 2</td>
  </tr>
  <tr>
    <th>Header 3</th>
    <th>Datum 2</td>
  </tr>
</table>
<script src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
<script>
  google.load("jquery", "1.3.1");
  google.setOnLoadCallback(function() {
    $(function() {
      $("tr:has(th):not(:has(td))").hide();
    });
  });
</script>
</body>
</html>
cletus
jQuery is friggin amazing. That is all.
Jeremy Ricketts
+5  A: 

If possible, it would be ideal to enclose your table header inside a <thead> element

<table>
    <thead>
        <tr>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
        </tr>
    </tbody>
</table>

That way, selecting your table header would be as simple as:

$('thead');

Or selecting only the <tr>

$('thead tr');

Your markup would then be more readable, and styling your table becomes easier, as you can more easily target elements in the header or body of your table.

steve.platz