「jQuery」children()でテーブルの行数を取得する
環境
jquery 3.6.0
書式
$(“テーブルのID名 tbody").children().length
テーブルのtbody配下の要素の件数はテーブルの行数です
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//計算ボタンを押すとテーブルの行数をアラート表示する
$("#btnShow").click(function(){
var res = $("#tbcity tbody").children().length;
alert("行数: " + res);
});
});
</script>
</head>
<body>
<table id="tbcity">
<tr><td>東京</td></tr>
<tr><td>大阪</td></tr>
<tr><td>福岡</td></tr>
<tr><td>川崎</td></tr>
</table>
<input type="button" id="btnShow" value="計算">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//計算ボタンを押すとテーブルの行数をアラート表示する
$("#btnShow").click(function(){
var res = $("#tbcity tbody").children().length;
alert("行数: " + res);
});
});
</script>
</head>
<body>
<table id="tbcity">
<tr><td>東京</td></tr>
<tr><td>大阪</td></tr>
<tr><td>福岡</td></tr>
<tr><td>川崎</td></tr>
</table>
<input type="button" id="btnShow" value="計算">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ //計算ボタンを押すとテーブルの行数をアラート表示する $("#btnShow").click(function(){ var res = $("#tbcity tbody").children().length; alert("行数: " + res); }); }); </script> </head> <body> <table id="tbcity"> <tr><td>東京</td></tr> <tr><td>大阪</td></tr> <tr><td>福岡</td></tr> <tr><td>川崎</td></tr> </table> <input type="button" id="btnShow" value="計算"> </body> </html>
結果
「計算」ボタンを押すとテーブルの行数を「4」表示する。