How to create HTML Table dynamically using Java Script

In this article I will explain with an example, how to create a dynamic Table in HTML at runtime using JavaScript.
The columns, rows and cells will be dynamically created in the Table using JavaScript.
In this example we add a new table to the page when a button is clicked.
Html :
<button class="btn-dark mb-3" onclick="GetTable()">Click here</button>
<div id="DynamicTable"></div>

JavaScript :

function GetTable() {
            //Build an array containing Customer records.
            var students = new Array();
            students.push(["Customer Id", "Name", "Country"]);
            students.push([1, "Rahul", "United States"]);
            students.push([2, "Anamy", "India"]);
            students.push([3, "Jhon", "France"]);
            students.push([4, "Robert", "UK"]);

            //Create a HTML Table element.
            var table = document.createElement("TABLE");
            table.border = "1";

            //Get the count of columns.
            var columnCount = students[0].length;

            //header row.
            var row = table.insertRow(-1);
            for (var i = 0; i < columnCount; i++) {
                var headerCell = document.createElement("TH");
                headerCell.innerHTML = students[0][i];

            //table data rows.
            for (var i = 1; i < students.length; i++) {
                row = table.insertRow(-1);
                for (var j = 0; j < columnCount; j++) {
                    var cell = row.insertCell(-1);
                    cell.innerHTML = students[i][j];

            var dynamicTable = document.getElementById("DynamicTable");
            dynamicTable.innerHTML = "";

Output :

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories