JavaScript deleteRow関数でtableのtr要素を削除する
環境
Google Chrome 115.0.5790.171(Official Build) (64 ビット)
Windows 11 Pro 64bit
構文
const 変数名 = document.getElementById(tableのID名);
最初tr要素を削除します
変数名.tBodies[0].deleteRow(0)
最後tr要素を削除します
変数名.tBodies[0].deleteRow(0)
deleteRow(位置)を使って、tr要素を削除します。
使用例
<!DOCTYPE html>
<html>
<body>
<table id="city" border="1">
<tbody>
<tr>
<th>yamada</th>
<th>10</th>
</tr>
<tr>
<th>oosaki</th>
<th>20</th>
</tr>
<tr>
<th>oohashi</th>
<th>30</th>
</tr>
</tbody>
</table>
<br>
<button onclick="funA()">表示</button>
<script>
function funA() {
const tbs = document.getElementById('city');
// 最初tr要素を削除
tbs.tBodies[0].deleteRow(0);
// 最後tr要素を削除
tbs.tBodies[0].deleteRow(-1);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<table id="city" border="1">
<tbody>
<tr>
<th>yamada</th>
<th>10</th>
</tr>
<tr>
<th>oosaki</th>
<th>20</th>
</tr>
<tr>
<th>oohashi</th>
<th>30</th>
</tr>
</tbody>
</table>
<br>
<button onclick="funA()">表示</button>
<script>
function funA() {
const tbs = document.getElementById('city');
// 最初tr要素を削除
tbs.tBodies[0].deleteRow(0);
// 最後tr要素を削除
tbs.tBodies[0].deleteRow(-1);
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <table id="city" border="1"> <tbody> <tr> <th>yamada</th> <th>10</th> </tr> <tr> <th>oosaki</th> <th>20</th> </tr> <tr> <th>oohashi</th> <th>30</th> </tr> </tbody> </table> <br> <button onclick="funA()">表示</button> <script> function funA() { const tbs = document.getElementById('city'); // 最初tr要素を削除 tbs.tBodies[0].deleteRow(0); // 最後tr要素を削除 tbs.tBodies[0].deleteRow(-1); } </script> </body> </html>
実行結果
表示ボタンを押すと、最初tr要素と最後tr要素を削除します。