How to Get the Caption of a Table Element in JavaScript

08/03/2021

Contents

In this article, you will learn how to get the caption of a table element in JavaScript.

Getting the caption of a table element in JavaScript

If you want to get the caption of a table element using JavaScript, you can use several methods. Here are some of the most common approaches.

Using the caption property

The HTMLTableElement interface has a caption property that returns the caption of the table. Here’s an example:

<table>
  <caption>Table Caption</caption>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1, Column 1</td>
      <td>Row 1, Column 2</td>
    </tr>
    <tr>
      <td>Row 2, Column 1</td>
      <td>Row 2, Column 2</td>
    </tr>
  </tbody>
</table>
 
const table = document.querySelector("table");
const caption = table.caption.textContent;
console.log(caption); // "Table Caption"

In this example, we first select the table element using document.querySelector(). We then access the caption property of the table element and get its textContent property.

Using the getElementsByTagName() method

You can also use the getElementsByTagName() method to get the caption element and its text content. Here’s an example:

<table>
  <caption>Table Caption</caption>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1, Column 1</td>
      <td>Row 1, Column 2</td>
    </tr>
    <tr>
      <td>Row 2, Column 1</td>
      <td>Row 2, Column 2</td>
    </tr>
  </tbody>
</table>
 
const table = document.querySelector("table");
const caption = table.getElementsByTagName("caption")[0].textContent;
console.log(caption); // "Table Caption"

In this example, we first select the table element using document.querySelector(). We then use the getElementsByTagName() method to get the caption element and access the first (and only) element in the resulting collection. We then get its textContent property.

Using the querySelector() method

You can also use the querySelector() method to select the caption element and get its text content. Here’s an example:

<table>
  <caption>Table Caption</caption>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1, Column 1</td>
      <td>Row 1, Column 2</td>
    </tr>
    <tr>
      <td>Row 2, Column 1</td>
      <td>Row 2, Column 2</td>
    </tr>
  </tbody>
</table>
 
const caption = document.querySelector("table caption").textContent;
console.log(caption); // "Table Caption"

In this example, we use the querySelector() method to select the caption element directly using a CSS selector. We then get its textContent property.