用于获取HTML表的行数的JavaScript

时间:2010-06-16 13:12:50

标签: javascript html

如何使用JavaScript获取具有ID和名称的HTML table的行数?

5 个答案:

答案 0 :(得分:86)

您可以使用.rows property并查看.length,如下所示:

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

答案 1 :(得分:86)

基本上:

var rows = document.getElementById(tableId).getElementsByTagName("tr").length;

或者如果中间有<tbody>

var rows = document.getElementById(tableId).getElementsByTagName("tbody")[0].getElementsByTagName("tr").length;

答案 2 :(得分:10)

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

答案 3 :(得分:1)

如果表中有ID

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

如果表中有Class

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

如果表中有Name

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

注意:索引1代表<tbody>标签

答案 4 :(得分:0)

这是另一种选择,使用Jquery并仅获取tbody行(包含数据)并取消考虑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>