javascript tableのtFoot要素を取得する

javascript tableのtFoot要素を取得する

javascriptで、tableのtFoot要素を取得するサンプルコードを記述してます。「テーブル要素.tFoot」で取得することができます。サンプルコードは「tFoot」要素の色を変更するというものになります。

環境

  • OS windows11 home
  • ブラウザ chrome 107.0.5304.88

tFoot要素を取得

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

<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>
    <tfoot>
        <tr>
            <th scope="row">Totals</th>
            <td>60</td>
        </tr>
    </tfoot>
</table>

<script>

const elm = document.getElementById('tbl');

console.log(elm.tFoot.outerHTML);

</script>

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

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

console.log( tbl.tFoot.outerHTML );

サンプルコード

以下は、実行ボタンをクリックすると「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">
      <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-info btn-rounded ">実行</button>

  </div>

  <script>

    result.addEventListener('click', () => {
      tbl.tFoot.style.color = "red"
    });

  </script>

</body>

</html>

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