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

时间:2017-12-18 07:02:50

标签: javascript jquery

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 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

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

答案 2 :(得分: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();
});

答案 3 :(得分:0)

I found an answer from Ricky G at

jQuery: count number of rows in a table

Here's my code:

char aword[100];

To use:

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

Thanks and a tip of the hat to Ricky G!