JavaScript 获取 HTML 表的行数

如何使用 JavaScript 获得具有 id 和 name 的 HTML table的行数?

244209 次浏览

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

var rowCount = document.getElementById('myTableID').rows.length;

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.

$('tableName').find('tr').length

This is another option, using jQuery and getting only tbody rows (with the data) and desconsidering thead/tfoot.

$("#tableId > tbody > tr").length

console.log($("#myTableId > tbody > tr").length);
.demo {
width:100%;
height:100%;
border:1px solid #C0C0C0;
border-collapse:collapse;
border-spacing:2px;
padding:5px;
}


.demo caption {
caption-side:top;
text-align:center;
}


.demo th {
border:1px solid #C0C0C0;
padding:5px;
background:#F0F0F0;
}


.demo td {
border:1px solid #C0C0C0;
text-align:left;
padding:5px;
background:#FFFFFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
<caption>Table 1</caption>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan=4 style="background:#F0F0F0">&nbsp; </td>
</tr>
</tfoot>
</table>

If the table has an ID:

const tableObject = document.getElementById(tableId);
const rowCount = tableObject[1].childElementCount;

If the table has a Class:

const tableObject = document.getElementsByClassName(tableClass);
const rowCount = tableObject[1].childElementCount;

If the table has a Name:

const tableObject = document.getElementsByTagName('table');
const rowCount = tableObject[1].childElementCount;

Note: index 1 represents <tbody> tag