javascript tableのcaption要素を作成する

javascript tableのcaption要素を作成する

javascriptで、tableのcaption要素を作成するサンプルコードを記述してます。テーブルの要素を取得して「createCaption」で可能です。

環境

  • OS windows11 home
  • ブラウザ chrome 107.0.5304.88

caption要素を作成

caption要素を作成するには、「テーブル要素.createCaption」で可能です。

<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');

const tc = elm.createCaption();

// テキストノードを追加
tc.appendChild(document.createTextNode('追加'));

</script>

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

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

const tc = tbl.createCaption();

tc.appendChild(document.createTextNode('追加'));

サンプルコード

以下は、実行ボタンをクリックすると「table」にcaption要素を追加するだけのサンプルコードとなります。

※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', () => {

      const tc = tbl.createCaption();
      tc.appendChild(document.createTextNode('追加しました'));

    });

  </script>

</body>

</html>

追加されていることが確認できます。