Obtenga el número de filas en una tabla HTML [duplicado]

I've browsed the Internet looking for an answer on this but I can't find a solution. I want to count the amount of rows my HTML table has in when a link button is pressed. Can someone help me out please?

Esto es lo que tengo hasta ahora:

 $('#HypSelectAll').click(function () {
     var count = $('#gvPerformanceResult').children().length;
     for (i = 0; i < count; i++) {

But some reason it returns 0 even though I have about 12 rows in my table? I've checked my ID name and it's correct.

preguntado el 31 de julio de 12 a las 15:07

5 Respuestas

var x = document.getElementById("myTable").rows.length;

respondido 21 mar '16, 08:03

Is there a way to subset this to rows meeting a certain condition? - Hack-R


var count = $('#gvPerformanceResult tr').length;

Respondido 31 Jul 12, 15:07

Note that this will not give the expected result with nested tables, i.e. tables that contain other tables. - Sjoerd

The following code assumes that your table has the ID 'MyTable'

<script language="JavaScript">
var oRows = document.getElementById('MyTable').getElementsByTagName('tr');
var iRowCount = oRows.length;

alert('Your table has ' + iRowCount + ' rows.');

Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)

Respondido 31 Jul 12, 15:07

For my own personal knowledge, what is not cross browser in this solution ? - Al_th

getElementsByTagName varies somewhat from IE, FF and (Chrome, Webkit, Opera) IE7/8 have a habit of returning 0 for your example. Firefox can get confused with namespaces. In the later doesnt support the same style of namespaces. webdeveloper.com/forum/showthread.php?t=248215 webbugtrack.blogspot.co.uk/2007/09/… msdn.microsoft.com/en-us/library/ie/ms536439(v=vs.85).aspx (comments) I'd avoid getElementsByTagName. - Marcos Broadhurst

In the DOM, a tr element is (implicitly or explicitly) a child of tbody, theado tfoot, no un hijo de table (hence the 0 you got). So a general answer is:

var count = $('#gvPerformanceResult > * > tr').length;

This includes the rows of the table but excludes rows of any inner table.

Respondido 31 Jul 12, 17:07

O puedes usar: var count = $('#gvPerformanceResult tr').length; - w.daya

Well it depends on what you have in your table.

its one of the following If you have only one table

var count = $('#gvPerformanceResult tr').length;

If you are concerned about sub tables but this wont work with tbody and thead (if you use them)

var count = $('#gvPerformanceResult>tr').length;

Where by this will work (but is quite frankly overkill.)

var count = $('#gvPerformanceResult>tbody>tr').length;

Respondido 31 Jul 12, 16:07

The second selector won't work at all. - PernoReloj

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.