How to display array list into dynamic table Using JavaScript

Display an array list into a dynamic html table. In this Java Script example, let’s create a dynamic array and create an HTML table to display the data in table format.

Problem Statement

In this, we have to create a dynamic table using JS to create an HTML file that uses the JS function that will return the table on the output screen.

Solution

  • Create HTML file as xyz.html
  • Create an input type button to generate a table
  • Create array that containing customer records var customers = new Array();
  • For creating html table element use a document.createElement(“TABLE“);  in that add content “customer id” “name” “country“.
  • Add columns and rows in table for that use customers[0].length and table.insertRow(-1)
  • Use for loop in the first loop we are creating a header using  headerCell = document.createElement(“TH“);
  • Add appendchild() method that allows us to add a node to end of the list of child node row.appendChild(headerCell);
  • In next loop, we are inserting a row then adding each cell by using the insertCell() method
  • In the last append table by using dvTable.appendChild(table);
  • Display output on the screen

JS code to create a dynamic table

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic table in JS</title>
</head>
<body>
    <input type="button" value="Generate Table" onclick="GenerateTable()" />
<hr />
<div id="dvTable"></div>
 
 <script type="text/javascript">
    function GenerateTable() {
        var customers = new Array();
        customers.push(["Customer Id", "Name", "Country"]);
        customers.push([1, "Ranbir", "India"]);
        customers.push([2, "Jhon", "US"]);
        customers.push([3, "Kemal", "Turkey"]);
        customers.push([4, "Kabir", "Canada"]);
 
        var table = document.createElement("TABLE");
        table.border = "1";
 
        var columnCount = customers[0].length;
 
        var row = table.insertRow(-1);
        for (var i = 0; i < columnCount; i++) {
            var headerCell = document.createElement("TH");
            headerCell.innerHTML = customers[0][i];
            row.appendChild(headerCell);
        }
 
    
        for (var i = 1; i < customers.length; i++) {
            row = table.insertRow(-1);
            for (var j = 0; j < columnCount; j++) {
                var cell = row.insertCell(-1);
                cell.innerHTML = customers[i][j];
            }
        }
 
        var dvTable = document.getElementById("dvTable");
        dvTable.innerHTML = "";
        dvTable.appendChild(table);
    }
</script>
 
</body>
</html>

Output