542

How do I count the number of tr elements within a table using jQuery?

I know there is a similar question, but I just want the total rows.

Community
  • 1
  • 1

12 Answers12

1054

Use a selector that will select all the rows and take the length.

var rowCount = $('#myTable tr').length;

Note: this approach also counts all trs of every nested table!

Community
  • 1
  • 1
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 11
    $('#myTable tr').size() will return the same value. – Garry Shutler Jul 19 '09 at 14:07
  • 34
    @Garry -- the docs indicate that length is preferred over size() because it's faster. – tvanfosson Jul 19 '09 at 14:19
  • 14
    .size() calls .length internally – redsquare Jul 19 '09 at 15:44
  • I've always wondered what the point of the size method was. Did length not exist originally and it's just there for backward compatibility? – Matthew Crumley Nov 19 '09 at 03:28
  • 2
    It has a length property because it's an array. I don't know enough of the history of jQuery to know whether the jQuery object always extended an array. – tvanfosson Nov 19 '09 at 11:35
  • 1
    After a little research, I can only find data supporting that the .size method was implemented specifically for textual elements (ie., input type="text", textarea, etc). – DevlshOne Sep 18 '12 at 22:47
  • 73
    This will also count tr in the thead... $('#myTable tbody tr').length; will count those only in table bodies.. – Dave Lawrence Jul 18 '13 at 11:20
  • @TomRegan - I think that's only true if you are storing the result in a variable. In that case, yes you would need to redo the selection since the previous one was storing the results on the table before the addition - or are you taking the length of the result of `after` - that wouldn't do the same thing at all. – tvanfosson Feb 20 '14 at 20:10
  • those who gets confused with `.size()` and `.length`, check this out http://stackoverflow.com/a/14202745/5289704 – Aravindh Gopi Apr 08 '17 at 07:53
  • How can we calculate the number of rows for **a specific value** in a `td`? Say there are 10 rows and some of the rows have value **Manila** in the `city` column, how do we get all those rows with **Manila**? – Love Putin Not War May 15 '20 at 05:04
  • How to do it when the table is submitted as variable (and not via an ID)? – principal-ideal-domain Mar 10 '23 at 13:08
202

If you use <tbody> or <tfoot> in your table, you'll have to use the following syntax or you'll get a incorrect value:

var rowCount = $('#myTable >tbody >tr').length;
James Moberg
  • 2,156
  • 1
  • 13
  • 2
  • 1
    I'm using but I get the same value – Kreker Jun 05 '12 at 14:58
  • 1
    use $('#myTable >tbody:last >tr').length; – Riccardo Bassilichi Jul 26 '12 at 11:14
  • You must also remember that if you use this solution, you won't actually get a COUNT since, by definition, the 'length' attribute is zero-based. – DevlshOne Sep 18 '12 at 22:43
  • 7
    @DevlshOne That is not true, length is not zero base, check the documentation: http://api.jquery.com/length/ – Miguel May 01 '13 at 16:01
  • 1
    When you have nested tables, this will only count the rows in the specified table, which is what I needed. – GilShalit Oct 01 '13 at 05:51
  • Is there a difference between $('#myTable >tbody >tr') and $('#myTable tbody tr') ? – FrenkyB Apr 05 '17 at 12:56
  • @FrenkyB Technically yes. In terms of results it only matters if the table with id myTable has nested tables. > signifies 'direct child' is css. – AntonChanning Mar 18 '19 at 12:04
  • @AntonChanning : How can we calculate the number of rows for **a specific value** in a `td`? Say there are 10 rows and some of the rows have value **Manila** in the `city` column, how do get all those rows with **Manila**? – Love Putin Not War May 15 '20 at 04:44
  • 1
    @user12379095 Something like this: https://stackoverflow.com/questions/32101764/trouble-getting-count-of-table-rows-that-contain-certain-text – AntonChanning Jun 02 '20 at 07:09
52

Alternatively...

var rowCount = $('table#myTable tr:last').index() + 1;

jsFiddle DEMO

This will ensure that any nested table-rows are not also counted.

DevlshOne
  • 8,357
  • 1
  • 29
  • 37
35

Well, I get the attr rows from the table and get the length for that collection:

$("#myTable").attr('rows').length;

I think that jQuery works less.

Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
jjroman
  • 663
  • 7
  • 10
  • 2
    +1 - Good for the scenario where you are passed element that contains a table eg var rowCount = $(element).attr('rows').length; – Nicholas Murray Jan 27 '12 at 11:41
  • 11
    Using JQuery v1.9.0 and I must use prop() to access 'rows': $("#myTable").prop('rows').length; (Chromium 24) – nvcnvn Feb 04 '13 at 14:23
18

Here's my take on it:

//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

USAGE:

var rowCount = $('#productTypesTable').rowCount();
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
Ricky Gummadi
  • 4,559
  • 2
  • 41
  • 67
  • Very nice function @Ricky G, useful to do several things example this function can be called for html generated from backend instead of dom as well.. Thanks – Dhaval dave Feb 01 '16 at 14:09
12

I got the following:

jQuery('#tableId').find('tr').index();
chifliiiii
  • 2,231
  • 3
  • 28
  • 37
11

try this one if there is tbody

Without Header

$("#myTable > tbody").children.length

If there is header then

$("#myTable > tbody").children.length -1

Enjoy!!!

BornToCode
  • 207
  • 2
  • 7
  • 1
    It is missing () after chidlren => $("#myTable > tbody").children().length – DrB Feb 28 '16 at 07:45
  • 1
    The header should be enclosed in `` which should come before ``. So the -1 should not be needed, if the table is properly designed according to the standard. – ilpelle Apr 12 '16 at 12:29
  • problem is , when datatable has no record it shows length as 1, because datatable render a empty row with class "odd" in datatable ..... – Syed Ali Apr 25 '16 at 05:25
  • I have a dynamic table on a UserScript and this was the only solution that worked – brasofilo Mar 12 '17 at 19:20
8

I found this to work really well if you want to count rows without counting the th and any rows from tables inside of tables:

var rowCount = $("#tableData > tbody").children().length;
Zoe
  • 181
  • 1
  • 2
  • 11
7

I needed a way to do this in an AJAX return, so I wrote this piece:

<p id="num_results">Number of results: <span></span></p>

<div id="results"></div>

<script type="text/javascript">
$(function(){
    ajax();
})

//Function that makes Ajax call out to receive search results
var ajax = function() {
    //Setup Ajax
    $.ajax({
        url: '/path/to/url', //URL to load
        type: 'GET', //Type of Ajax call
        dataType: 'html', //Type of data to be expected on return
        success: function(data) { //Function that manipulates the returned AJAX'ed data
            $('#results').html(data); //Load the data into a HTML holder
            var $el = $('#results'); //jQuery Object that is holding the results
            setTimeout(function(){ //Custom callback function to count the number of results
                callBack($el);
            });
        }
    });
}

//Custom Callback function to return the number of results
var callBack = function(el) {
    var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
    $('#num_results span').text(length); //Write the counted results to the DOM
}
</script>

Obviously this is a quick example, but it may be helpful.

dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189
6
row_count =  $('#my_table').find('tr').length;
column_count =  $('#my_table').find('td').length / row_count;
Cybernetic
  • 12,628
  • 16
  • 93
  • 132
1

var trLength = jQuery('#tablebodyID >tr').length;

Olamigoke Philip
  • 1,035
  • 8
  • 10
sivaprakash
  • 167
  • 1
  • 4
  • 13
0
document.getElementById("myTable").rows.length;
Kuro Neko
  • 795
  • 12
  • 19
Hasan Zafari
  • 355
  • 2
  • 6
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Mar 17 '23 at 22:59