Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Get the number of rows in a table body

Tags:

jquery

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>John</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 image 447
user336786 Avatar asked May 12 '10 14:05

user336786


People also ask

How do I count the number of rows in a table?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How can I count the number of rows and columns in a table using jQuery?

columnCount = function() { return $('th', $(this). find('tbody')). length; }; var rowctr = $('#table1'). rowCount(); var colctr = $('#table1').

How can get TD of TR in jQuery?

jQuery(". dname"). find("tr td:eq(1)"). val();


3 Answers

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.

like image 63
SLaks Avatar answered Oct 24 '22 21:10

SLaks


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
like image 43
Scott Ivey Avatar answered Oct 24 '22 22:10

Scott Ivey


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

like image 23
John Avatar answered Oct 24 '22 22:10

John