jQuery Table Rows Count Examples
Did you want to count the rows of a table using jQuery but did not know where to start from? In get table rows count in jQuery by using just 1 line of code. Follow along to learn how.
Examples in jQuery to Get Table Rows Count
There are couple of ways to use jQuery to get table rows count. It can be obtained by using the .length property. We are going to look at them now by means of examples.
Example 1: Count Rows in Table using jQuery
<html>
<head>
<title>Count Table Rows with jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="my_table">
<tr>
<td>1</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>3</td>
<td>8</td>
</tr>
<tr>
<td>4</td>
<td>9</td>
</tr>
<tr>
<td>5</td>
<td>10</td>
</tr>
</table>
<button name="count_table_rows" id="count_table_rows">Count Table Rows</button>
<script type="text/javascript">
$('#count_table_rows').click(function() {
var rows = $("#my_table tr").length;
alert('Total Rows: '+rows);
});
</script>
</body>
</html>In the above example, simply click on the button and that will alert the number of rows in the table.
Example 2 – Count Rows in Table using jQuery
Alternately, instead of using .length property, you can use size() method to get table rows count. Simply use the following jQuery code instead of the one listed in the code above:
<script type="text/javascript">
$('#count_table_rows').click(function() {
var rows = $("#my_table tr").size();
alert('Total Rows: '+rows);
});
</script>The above code produces the same result as the earlier code.
jQuery length vs size()
Now that you have noticed that both length vs size() do the same thing, then what exactly is the difference between them. Functionality wise, there is no difference. They do the same thing. The .length property is preferred because it does not have the overhead of a function call and hence it is quicker to execute.
So now that you know the difference, use .length property from here on and make your code run even more faster.
That’s it for now!
Do you know of any other ways to get table rows count using jQuery? Feel free to suggest by commenting below.