Create a Table Element - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Table

Introduction

You can create a <table> element by using the document.createElement() method:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
table, td {
    border: 1px solid black;
}
</style>//from ww w  .  java 2s .  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()">create a thead element for the table</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>

Related Tutorials