Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying all rows within a table <tbody> element using jQuery

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();
like image 835
cw84 Avatar asked Oct 15 '09 20:10

cw84


2 Answers

You can use the below if you know the table id.

var trs = $("#tableid").find("tbody>tr");
like image 126
Ally Avatar answered Sep 17 '22 09:09

Ally


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

HTML

<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>
</table>

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.

like image 24
Omar Avatar answered Sep 18 '22 09:09

Omar