Russell Eubanks
Russell Eubanks

Reputation: 27

What is the jQuery syntax to use when trying to get the number of rows in an HTML table where the table selector is a variable

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?

Upvotes: 0

Views: 83

Answers (4)

Russell Eubanks
Russell Eubanks

Reputation: 27

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!

Upvotes: 0

Philipp Wrann
Philipp Wrann

Reputation: 1849

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();
});

Upvotes: 0

Aslan Mammadrzayev
Aslan Mammadrzayev

Reputation: 281

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

Upvotes: 0

Satpal
Satpal

Reputation: 133423

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;

Upvotes: 2

Related Questions