Javascript DOM HTML Table createTHead() Method

Introduction

Create a <thead> element and insert a <tr> and <td> element to it:

Click the button to create a thead element for the table.

The thead element must have one or more tr elements inside of it.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
table, td {
  border: 1px solid black;
}
</style>// w ww . j  av a 2 s  .co  m
</head>
<body>
<table id="myTable">
  <tr>
    <td>cell 1</td>
    <td>cell 2</td>
  </tr>
  <tr>
    <td>cell 3</td>
    <td>cell 4</td>
  </tr>
</table>
<button onclick="myFunction()">Test</button>

<script>
function myFunction() {
  var table = document.getElementById("myTable");
  var header = table.createTHead();
  var row = header.insertRow(0);
  var cell = row.insertCell(0);
  cell.innerHTML = "<b>This is a table header</b>";
}
</script>

</body>
</html>

The createTHead() method creates an empty <thead> element and adds it to the table.

If a <thead> element exists on the table, the createTHead() method returns the existing one, and does not create a new one.

The <thead> element must have one or more <tr> tags inside.

The createTHead() method returns the newly created or an existing <thead> element.




PreviousNext

Related