Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript to get rows count of a HTML table

How to get with JavaScript the rows count of a HTML table having id and name?

like image 246
kawtousse Avatar asked Jun 16 '10 13:06

kawtousse


People also ask

How can get number of rows in HTML table using jQuery?

Answer: Use the length Property You can simply use the length property to count or find the number of rows in an HTML table using jQuery. This property can be used to get the number of elements in any jQuery object.

How do you display a list of database data in an HTML table using JavaScript?

Something like this should work (and here's a fiddle to demonstrate: http://jsfiddle.net/83d4w/5/) : var newTr = null; var resetTr = true; $. each(list, function(index, list) { list[2]===null||list[2]===undefined||list[2]===''||isNaN(list[2])?


2 Answers

Given a

<table id="tableId">     <thead>         <tr><th>Header</th></tr>     </thead>     <tbody>         <tr><td>Row 1</td></tr>         <tr><td>Row 2</td></tr>         <tr><td>Row 3</td></tr>     </tbody>     <tfoot>         <tr><td>Footer</td></tr>     </tfoot> </table> 

and a

var table = document.getElementById("tableId"); 

there are two ways to count the rows:

var totalRowCount = table.rows.length; // 5 var tbodyRowCount = table.tBodies[0].rows.length; // 3 

The table.rows.length returns the amount of ALL <tr> elements within the table. So for the above table it will return 5 while most people would really expect 3. The table.tBodies returns an array of all <tbody> elements of which we grab only the first one (our table has only one). When we count the rows on it, then we get the expected value of 3.

like image 164
BalusC Avatar answered Sep 23 '22 18:09

BalusC


You can use the .rows property and check it's .length, like this:

var rowCount = document.getElementById('myTableID').rows.length; 
like image 28
Nick Craver Avatar answered Sep 21 '22 18:09

Nick Craver