tags:

views:

638

answers:

4

I am trying to retrieve all rows from within a <tbody> section of a table, but am unsure of the syntax for doing so. I've included a dummy table extract below and my latest attempt for achieving the task with jQuery!

Table extract:

<tbody>
 <tr>
  <th id="emergency" colspan="2">Emergency</th>
 </tr>
    <tr>
      <td>Emergency data</td>
      <td>Emergency data</td>
    </tr>
    <tr>
      <td>Emergency data</td>
      <td>Emergency data</td>
    </tr>
</tbody>
<tbody> 
 <tr>
  <th id="urgent" colspan="2">Urgent</th>
 </tr>
    <tr>
      <td>Urgent Data</td>
      <td>Urgent Data</td>
    </tr>
    <tr>
      <td>Urgent Data</td>
      <td>Urgent Data</td>
    </tr>
 </tbody>

jQuery code:

var emergencyRows = $table.find('#emergency').children().get();
+1  A: 

Try:

var emergencyRows = $("th#emergency").parent().parent().find("tr:gt(0)");

which should get you all rows that aren't the header row.

richsage
+1  A: 

My suggestions is to place the ID attributes on the tbody rather than the first row of each one.

Table

<tbody id="emergency">
 <tr>
  <th colspan="2">Emergency</th>
 </tr>
 <tr>
   <td>Emergency data</td>
   <td>Emergency data</td>
 </tr>
 <tr>
   <td>Emergency data</td>
   <td>Emergency data</td>
 </tr>
</tbody>
<tbody id="urgent"> 
 <tr>
  <th colspan="2">Urgent</th>
 </tr>
 <tr>
   <td>Urgent Data</td>
   <td>Urgent Data</td>
 </tr>
 <tr>
   <td>Urgent Data</td>
   <td>Urgent Data</td>
 </tr>
 </tbody>

Jquery

var emergencyRows = $("tbody#emergency").find("tr:gt(0)");
var urgentRows = $("tbody#urgent").find("tr:gt(0)");

The jQuery snippet will get all the respective rows with the exception of the first rows.

Baddie
+1  A: 

This is probably the cleanest

$('#emergency').closest('tbody').children(); //only returns first child element, so the <tr>'s
Agent_9191
+1  A: 

From your example, it seems like you might want "all rows except for the one containing #emergency". If that's the case, you can use the following:

$('#emergency').closest('tr').siblings();

Note that #emergency need not be a <tr /> or <th /> or anything in particular. It could be any element within a table cell.

Annabelle