javascript tableのtbody要素を取得する
- 作成日 2022.10.14
- javascript
- javascript

javascriptで、tableのtbody要素を取得するサンプルコードを記述してます。
環境
- OS windows11 home
- ブラウザ chrome 106.0.5249.103
tbody要素を取得
tbody要素を取得するには、「テーブル要素.tBodies[0]」で取得します。
<table id="tbl">
<thead>
<tr>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<th>itiro</th>
<th>10</th>
</tr>
<tr>
<th>jiro</th>
<th>20</th>
</tr>
<tr>
<th>saburo</th>
<th>30</th>
</tr>
</tbody>
</table>
<script>
const elm = document.getElementById('tbl');
console.log(elm.tBodies[0].outerHTML);
</script>
実行結果をみると取得されていることが確認できます。

また、javascript部はdocument.getElementByIdを省略して記述することも可能です。
console.log( tbl.tHead.outerHTML );
サンプルコード
以下は、実行ボタンをクリックするとtableのtbodyの色を変更するだけのサンプルコードとなります。
※cssには「Material Design for Bootstrap」を使用してます。関数はアロー関数を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
<!-- MDB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.1.0/mdb.min.css" rel="stylesheet" />
</head>
<body>
<div class="container text-center w-25" style="margin-top:150px">
<table id="tbl" class="table p-4">
<thead>
<tr>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<th>itiro</th>
<th>10</th>
</tr>
<tr>
<th>jiro</th>
<th>20</th>
</tr>
<tr>
<th>saburo</th>
<th>30</th>
</tr>
</tbody>
</table>
<button id="result" class="btn btn-primary btn-rounded ">実行</button>
</div>
<script>
result.addEventListener('click', () => {
tbl.tBodies[0].style.color = "red"
});
</script>
</body>
</html>
変更されていることが確認できます。

-
前の記事
Dart リスト(配列)から値を抽出する 2022.10.14
-
次の記事
Google ドライブ 履歴ウィンドウの表示・非表示を切り替えるショートカットキー 2022.10.14
コメントを書く