htmlのテーブルの列で数値をインクリメントして設定する

目次

01. 目的

02. コード

 

目的

htmlのテーブルの列で数値をインクリメントして設定する

上記図では、Noの列の数値は、JavaScriptでインクリメントしてセットしています。

コード

<style>
  table {
    border-collapse: collapse;
  }

  th,
  td {
    border: 1px solid #999;
  }
</style>

<table id="myTable">
  <thead>
    <tr>
      <th class="no-col">No</th>
      <th>Name</th>
      <th>score</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>tanaka</td>
      <td>85</td>
    </tr>
    <tr>
      <td></td>
      <td>sato</td>
      <td>90</td>
    </tr>
    <tr>
      <td></td>
      <td>suzuki</td>
      <td>80</td>
    </tr>
  </tbody>
</table>

<script>
  // 自動で No 列をインクリメントして埋める
  const table = document.getElementById("myTable");
  const rows = table.querySelectorAll("tbody tr");

  rows.forEach((row, index) => {
    row.cells[0].textContent = index + 1;
  });
</script>

JavaScriptのforEachで縦の列の数だけ繰り返して数値をインクリメントしてセットしています。

関連の記事

JavaScript forEach 配列を関数に渡して1回ずつ実行

△上に戻る