0

I need to get the number of rows in a table using a variable as the table selector. I get the table with this:

var table_element = $(this).prev('table.w2bw2c-with-artists-table');

I tried this from a previous post but got an error that length was undefined.

var new_with_artist_index = $(table_element).rows.length;

I have seen these methods used to find the number of rows in a table:

var rowCount = $("#tblEmployee td").closest("tr").length;
var rowCount = $('#myTable tbody tr').length;

How can I use one of these methods where the table selector is a variable instead of an ID? Or is there a better way?

4 Answers4

2

You can just use .find() method on jQuery object.

var rowCount = table_element.find('tbody tr').length; 

Or, You could get the native table using [] or .get() then use .rows property

var rowCount = table_element[0].rows.length;
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

var row = $("#tblEmployee td").find("tr"); var rowCount = row.length;

0

Many ways to do this:

1. jQuery find method

$(tableElement).find('tr').length

2. jQuery context parameter (i call it that way)

$('tr', tableElement).length

3. Plain Javascript

tableElement.querySelectorAll('tr').length

As you see the shortest would be the second variant, i think its also very clear, so if you can utilize jQuery, go for that variant. If you dont have jQuery in your library yet you should probably use the third variant.

querySelectorAll is defined for all DOM Elements and returns a NodeList. There is also a querySelector function, that will return the first match of the selector (so a single Element or null if nothing matches).

NodeList does not extend Array, so if you want to iterate the list, you need to do it that way:

[].forEach.call(tableElement.querySelectorAll('tr'), function(element) {
    doSomething();
});
Philipp Wrann
  • 1,751
  • 3
  • 19
  • 29
  • Thanks Philipp. I liked your alternative #2 better than the solution I found earlier and it worked great. A tip of the hat to you, too! – Russell Eubanks Dec 18 '17 at 08:09
0

I found an answer from Ricky G at

jQuery: count number of rows in a table

Here's my code:

//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;
};

To use:

var table_element = $(this).prev('table.w2bw2c-with-artists-table');
var new_with_artist_index = $(table_element).rowCount();

Thanks and a tip of the hat to Ricky G!