javascript tableのtfoot要素を作成する
- 作成日 2022.10.19
- javascript
- javascript
javascriptで、tableのtfoot要素を作成するサンプルコードを記述してます。
環境
- OS windows11 home
- ブラウザ chrome 106.0.5249.103
tfoot要素を作成
tfoot要素を作成するには、「テーブル要素.createTFoot」で可能です。
<table id="tbl">
<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 tbl = document.getElementById('tbl');
// tfoot要素を追加
const theElm = tbl.createTFoot();
// tr要素追加
const trElm = theElm.insertRow();
// th要素追加
let thElm = document.createElement('th');
// テキストノード追加
thElm.appendChild(document.createTextNode('TOTAL'));
// th要素を追加
trElm.appendChild(thElm);
// th要素追加
thElm = document.createElement('th');
// テキストノード追加
thElm.appendChild(document.createTextNode('60'));
// th要素をtr要素に追加
trElm.appendChild(thElm);
</script>
実行結果をみると作成されていることが確認できます。
また、javascript部はdocument.getElementByIdを省略して記述することも可能です。
// const tbl = document.getElementById('tbl'); ← このコードを省略可能
// tfoot要素を追加
const theElm = tbl.createTFoot();
サンプルコード
以下は、実行ボタンをクリックすると「table」にtfoot要素を追加するだけのサンプルコードとなります。
※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">
<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-success btn-rounded ">実行</button>
</div>
<script>
result.addEventListener('click', () => {
// tfoot要素追加
const theElm = tbl.createTFoot();
// tr要素追加
const trElm = theElm.insertRow();
// th要素追加
let thElm = document.createElement('th');
// テキストノード追加
thElm.appendChild(document.createTextNode('TOTAL'));
// th要素を追加
trElm.appendChild(thElm);
// th要素追加
thElm = document.createElement('th');
// テキストノード追加
thElm.appendChild(document.createTextNode('60'));
// th要素をtr要素に追加
trElm.appendChild(thElm);
});
</script>
</body>
</html>
追加されていることが確認できます。
-
前の記事
kotlin mutableMapに指定した値が含まれているかを判定する 2022.10.19
-
次の記事
GAS スプレッドシートで範囲を指定してセルを選択する 2022.10.19
コメントを書く