javascript tableのcaption要素を取得する

javascript tableのcaption要素を取得する

javascriptで、tableのcaption要素を取得するサンプルコードを記述してます。

環境

  • OS windows11 home
  • ブラウザ chrome 106.0.5249.103

caption要素を取得

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

<table id="tbl">
    <caption>title</caption>
    <tr>
        <th>name</th>
        <th>age</th>
    </tr>
    <tr>
        <th>itiro</th>
        <th>10</th>
    </tr>
    <tr>
        <th>jiro</th>
        <th>20</th>
    </tr>
    <tr>
        <th>saburo</th>
        <th>30</th>
    </tr>
</table>

<script>

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

console.log( elm.caption.outerHTML );

</script>

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

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

console.log( tbl.caption.outerHTML );

サンプルコード

以下は、ボタンをクリックすると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 table-striped p-4">
      <caption>title</caption>
      <tr>
        <th>name</th>
        <th>age</th>
      </tr>
      <tr>
        <th>itiro</th>
        <th>10</th>
      </tr>
      <tr>
        <th>jiro</th>
        <th>20</th>
      </tr>
      <tr>
        <th>saburo</th>
        <th>30</th>
      </tr>
    </table>

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

  </div>

  <script>

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

  </script>

</body>

</html>

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