javascript tableのtr要素を作成する
- 作成日 2022.09.08
- javascript
- javascript

javascriptで、tableのtr要素を作成するサンプルコードを記述してます。
環境
- OS windows11 home
- ブラウザ chrome 104.0.5112.101
tr要素を作成
tr要素を作成するには、「insertRow(位置)」で可能です。
※「-1」を指定すると最後尾に作成されます。
<table id="tbl">
<tbody>
<tr>
<th>itiro</th>
<th>10</th>
</tr>
</tbody>
</table>
<script>
const tbl = document.getElementById('tbl');
// tr要素追加(先頭に追加)
const trElm = tbl.tBodies[0].insertRow(0);
// th要素追加
let thElm = document.createElement('th');
// テキストノード追加
thElm.appendChild(document.createTextNode('jiro'));
// th要素を追加
trElm.appendChild(thElm);
// th要素追加
thElm = document.createElement('th');
// テキストノード追加
thElm.appendChild(document.createTextNode('20'));
// th要素をtr要素に追加
trElm.appendChild(thElm);
</script>
実行結果をみると作成されていることが確認できます。

また、javascript部はdocument.getElementByIdを省略して記述することも可能です。
// const tbl = document.getElementById('tbl'); ← このコードを省略可能
// tr要素追加(先頭に追加)
const trElm = tbl.tBodies[0].insertRow(0);
サンプルコード
以下は、実行ボタンをクリックすると「table」に「tr」要素を追加するだけのサンプルコードとなります。
※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-danger btn-rounded ">実行</button>
</div>
<script>
result.addEventListener('click', () => {
const tbl = document.getElementById('tbl');
// tr要素追加(最後に追加)
const trElm = tbl.tBodies[0].insertRow(-1);
// th要素追加
let thElm = document.createElement('th');
// テキストノード追加
thElm.appendChild(document.createTextNode('add'));
// th要素を追加
trElm.appendChild(thElm);
// th要素追加
thElm = document.createElement('th');
// テキストノード追加
thElm.appendChild(document.createTextNode('10'));
// th要素をtr要素に追加
trElm.appendChild(thElm);
});
</script>
</body>
</html>
追加されていることが確認できます。

-
前の記事
javascript 日付から四半期を取得する 2022.09.08
-
次の記事
C# foreachを途中で停止する 2022.09.08
コメントを書く