JavaScript allows you to create tables in dynamic way by adding rows and cells using HTML 5 table API.
In this article, we will create two different table using table API and JavaScript.
- dynamic table using rows
- dynamic table using rows and cells.
HTML 5 Table
HTML 5 table store information in rows and columns. The table consists of rows, columns, and table data. You can also provide a title to the table. Here is the list of tags used to create table.
- <table> – main table tag
- <tr> – table row
- <th> – table heading
- <td> – table data
- <legend> – a legend or title for table
Here is an example table.
<table>
<tr>
<th>fruit</th>
<th>price</th>
<th>in-stock</th>
</tr>
<tr>
<td>Oranges</td>
<td>Rs 200</td>
<td>Yes</td>
</tr>
<tr>
<td>Banana</td>
<td>Rs 100</td>
<td>No</td>
</tr>
</table>
Visit codepen.io
to see the output
See the Pen HTML 5 Table by Girish (@Girish2500) on CodePen.
Table Using Rows Only
In JavaScript, you can create table dynamically using rows only. To create a row for table, we will use insertRow()
API.
HTML 5 Code
<table id="mytable">
</table>
<br/>
<button onclick="createRow()">Insert</button>
In the table above, we are not using any kind of rows or data. The table is an empty container and row and data will be dynamically generated.
JavaScript Code
function createRow(){
//access the table and store it in a variable
var table = document.querySelector("#mytable");
//create rows and store it in a variable
var row = table.insertRow();
//now need to give some data to the table
row.innerHTML = "<td>data1</td><td>data2</td><td>data3</td>";
}
Visit codepen
to view the output.
See the Pen HTML5 Dynamic Table 1 by Girish (@Girish2500) on CodePen.
Table Using Rows and Cells
The method to create a dynamic table using rows and cells is the same. In this section, we will create the table will cells because we do not want to add HTML <td>.
<table id="myTable">
<caption>Dynamic table row using Cells</caption>
<tr><th scope="col">Name</th><th scope="col">Age</th></tr>
</table><br/>
<button onclick="insertrow()">Insert</button>
<button onclick="deleterow()">Delete</button>
JavaScript Code
function insertrow(){
var table = document.querySelector('#myTable');
var row = table.insertRow();
var cell1 = row.insertCell();
cell1.innerHTML = "1";
var cell2 = row.insertCell();
cell2.innerHTML = "2";
}
function deleterow(){
var table = document.querySelector("#myTable");
table.deleteRow(1);
}
In the code above, we have created row and for each row we are adding two cell including dummy data.
Deleting a Row
It is also possible to delete the dynamic rows. The API that you use to delete row is deleteRow().
Visit codepen.io
to see the result.
See the Pen HTML 5 Dynamic Table 2 by Girish (@Girish2500) on CodePen.
The deleteRow(1) API will take index value of the row that you want to delete. The very first row has index of 0.