JQuery - Get the number of rows in a table body
I have an HTML table that is defined as follows:
<table id="myTable" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Birth Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Joh开发者_如何学Gon</td>
<td>Smith</td>
<td>03-11-1980</td>
</tr>
</tbody>
</table>
I want to understand how to determine how many rows are in the tbody
portion of my table, instead of the table in general. How do I use JQuery to determine how many rows are in the tbody portion of a table?
Thank you!
Like this:
$("#myTable > tbody > tr").length
The a > b
selector selects all b
elements that are direct children of an a
element. Therefore, this selector will not match rows in nested tables.
Have you tried...
$("#myTable tbody tr").length
UPDATE: as mentioned in the comment - the above example doesn't account for nested tables. If you want to cover that as well, you'd want to use the parent/child selectors instead.
$("#myTable > tbody > tr").length
var amountOfRows = $("#myTable tbody tr").length;
alert(amountOfRows);
The variable amountOfRows will hold the number of rows. You can also use $("#myTable tbody tr").size But that is a shortcut for .length
If used on nested tables see SLaks answer
use this if you don't have a table id or just want to generalize tables
$('table.table').find('tbody').children().length;
There are several different ways you can do this, here are two of them
var totalRows = $('tbody > tr > td').length
var totalRows2 = $('tbody').find('td').length
The var totalRows and totalRows2 will have the number of 'td'
that are inside tbody
精彩评论