How to Get the tHead Element of a Table in JavaScript

08/03/2021

Contents

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

Getting the thead element of a table in JavaScript

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

Using the tHead property

The HTMLTableElement interface has a tHead property that returns the <thead> element of the table. Here’s an example:

<table>
  <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 thead = table.tHead;
console.log(thead); // the <thead> element

In this example, we first select the table element using document.querySelector(). We then access the tHead property of the table element.

Using the getElementsByTagName() method

You can also use the getElementsByTagName() method to get the <thead> element. Here’s an example:

<table>
  <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 thead = table.getElementsByTagName("thead")[0];
console.log(thead); // the <thead> element

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

Using the querySelector() method

You can also use the querySelector() method to select the <thead> element directly using a CSS selector. Here’s an example:

<table>
  <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 thead = document.querySelector("table > thead");
console.log(thead); // the <thead> element

In this example, we use the querySelector() method to select the <thead> element directly using a CSS selector. We then access the resulting element.