tags:

views:

48

answers:

4

Hello,

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 my rows are in the tbody portion of a table?

Thank you!

+1  A: 

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
Scott Ivey
`length` is not a function. Also, this won't handle nested tables.
SLaks
@SLaks - yeah, realized I had that wrong after I typed it. updated my answer to fix the length issue. Good call on the nexted tables - you get my vote on your answer :)
Scott Ivey
+6  A: 

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.

SLaks
Wow! That's pretty cool. I had no idea you could do that in JQuery. JQuery continues to impress me. Thank you for sharing your knowledge!
A: 
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

John
This also won't handle nested tables.
SLaks
A: 

There are severall different ways you can do this, here are two of then

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

fabio