javascript tableのtr要素を全て取得する

javascript tableのtr要素を全て取得する

javascriptで、tableのtr要素を全て取得するサンプルコードを記述してます。テーブル要素に対して「rows」を指定すれば「HTMLCollection」として取得できます。取得して「HTMLCollection」はループ処理が可能なので、forなどを使用して全て取得します。

環境

  • OS windows11 home
  • ブラウザ chrome 108.0.5359.125

tr要素を全て取得

「tr」要素を全て取得するには、「テーブル要素.rows」で取得します。

<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.rows );

for (i = 0, len = elm.rows.length; i < len; i++) {
	console.log( elm.rows[i].outerHTML )
}

</script>

実行結果をみると取得されていることが確認できます。

また、javascript部はdocument.getElementByIdを省略して記述することも可能です。

console.log( tbl.rows );

また「HTMLCollection」は配列化すれば「forEach」を使用できるので、上記のjavascriptは以下のようにまとめて、1行で記述することもできます。

[...tbl.rows].forEach((v) => { console.log( v.outerHTML ) })

サンプルコード

以下は、実行ボタンをクリックすると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">
      <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>
      <tfoot>
        <tr>
          <th scope="row">Totals</th>
          <td>60</td>
        </tr>
      </tfoot>
    </table>

    <button id="result" class="btn btn-danger btn-rounded ">実行</button>

  </div>

  <script>

    result.addEventListener('click', () => {
      for (i = 0, len = tbl.rows.length; i < len; i++) {
        tbl.rows[i].style.color = "red"
      }
    });

  </script>

</body>

</html>

変更されていることが確認できます。