You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:

var table = document.createElement('table');
for (var i = 1; i < 4; i++) {
  var tr = document.createElement('tr');

  var td1 = document.createElement('td');
  var td2 = document.createElement('td');

  var text1 = document.createTextNode('Text1');
  var text2 = document.createTextNode('Text2');

  td1.appendChild(text1);
  td2.appendChild(text2);
  tr.appendChild(td1);
  tr.appendChild(td2);

  table.appendChild(tr);
}
document.body.appendChild(table);

Answer from Krzysztof on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 73378172 › drawing-html-table-with-dynamic-columns-rows
Drawing HTML table with dynamic columns/rows
Then you can use for … in to ... the static structure of the table, and then use document.createElement() and .appendChild() to add the dynamic elements to the table....
Top answer
1 of 10
95

You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:

var table = document.createElement('table');
for (var i = 1; i < 4; i++) {
  var tr = document.createElement('tr');

  var td1 = document.createElement('td');
  var td2 = document.createElement('td');

  var text1 = document.createTextNode('Text1');
  var text2 = document.createTextNode('Text2');

  td1.appendChild(text1);
  td2.appendChild(text2);
  tr.appendChild(td1);
  tr.appendChild(td2);

  table.appendChild(tr);
}
document.body.appendChild(table);

2 of 10
28

It is because you're only creating two td elements and 2 text nodes.


Creating all nodes in a loop

Recreate the nodes inside your loop:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table');

for (var i = 1; i < 4; i++) {
    var tr = document.createElement('tr');

    tr.appendChild( document.createElement('td') );
    tr.appendChild( document.createElement('td') );

    tr.cells[0].appendChild( document.createTextNode('Text1') )
    tr.cells[1].appendChild( document.createTextNode('Text2') );

    table.appendChild(tr);
}

tablearea.appendChild(table);

Creating then cloning in a loop

Create them beforehand, and clone them inside the loop:

var tablearea = document.getElementById('tablearea'),
    table = document.createElement('table'),
    tr = document.createElement('tr');

tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );

tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );

for (var i = 1; i < 4; i++) {
    table.appendChild(tr.cloneNode( true ));
}

tablearea.appendChild(table);

Table factory with text string

Make a table factory:

function populateTable(table, rows, cells, content) {
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.appendChild(document.createElement('td'));
            row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
        }
        table.appendChild(row);
    }
    return table;
}

And use it like this:

document.getElementById('tablearea')
        .appendChild( populateTable(null, 3, 2, "Text") );

Table factory with text string or callback

The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.

function populateTable(table, rows, cells, content) {
    var is_func = (typeof content === 'function');
    if (!table) table = document.createElement('table');
    for (var i = 0; i < rows; ++i) {
        var row = document.createElement('tr');
        for (var j = 0; j < cells; ++j) {
            row.appendChild(document.createElement('td'));
            var text = !is_func ? (content + '') : content(table, i, j);
            row.cells[j].appendChild(document.createTextNode(text));
        }
        table.appendChild(row);
    }
    return table;
}

Used like this:

document.getElementById('tablearea')
        .appendChild(populateTable(null, 3, 2, function(t, r, c) {
                        return ' row: ' + r + ', cell: ' + c;
                     })
        );
🌐
Stack Overflow
stackoverflow.com › questions › 23577796 › how-to-create-a-html-table-with-dynamic-column-inside-a-div
jquery - How to create a HTML table with dynamic column inside a div - Stack Overflow
<table> <thead> <tr> <th>Header Column</th> <th>Column 2</th> <th>Column 3</th> <th>Column 4</th> </tr> </thead> <tbody> <tr><th>Header</th><td>Cell 2</td><td>Cell 3</td><td>Cell 4</td></tr> <tr><th>Header</th><td>Cell 2</td><td>Cell 3</td><td>Cell 4</td></tr> <tr><th>Header</th><td>Cell 2</td><td>Cell 3</td><td>Cell 4</td></tr> <tr><th>Header</th><td>Cell 2</td><td>Cell 3</td><td>Cell 4</td></tr> </tbody> </table> ... @user3622611 You haven't mentioned with a single word how you receive your data to the view and what language you're about to use to make this dynamic. What you have in there, css and html, are static in nature and it's impossible to do anything dynamic with them. ... @mrdeveloper At present i want the columns to be empty and later i want to add click event in the column.
🌐
Medium
medium.com › @mcodrescu › create-dynamic-html-tables-9205cd66cb05
Create Dynamic HTML Tables. One common problem while working with… | by Marcus Codrescu | Medium
June 7, 2022 - With the following JavaScript code, you can take an array of objects and fill an HTML table dynamically. // The tableData parameter should be an array of json objects function fillTable(tableData) { //Selects the table head and body from the DOM let tableHead = document.querySelector("#tableHead"); let tableBody = document.querySelector("#tableBody"); // Column names, number of rows, number of columns let colNames = Object.keys(tableData[0]); let nCol = Object.keys(tableData[0]).length; let nRow = tableData.length; // Insert table head let firstrow = tableHead.insertRow(); for (let index = 0;
🌐
CodeWithFaraz
codewithfaraz.com › home › components › create dynamic html table using html, css and javascript
Create Dynamic HTML Table Using HTML, CSS and JavaScript
June 11, 2025 - Learn how to create a dynamic HTML table using HTML, CSS, and JavaScript. This step-by-step tutorial guides you through building an interactive table with features like adding, deleting, and editing rows.
🌐
GitHub
gist.github.com › jineeshjohn › 2044414
Dynamic html table rows and column creation with jQuery · GitHub
numberformat function round the given number and GroupAnalyse.$results is my jquery instance (like GroupAnalyse.$results=$('#myTableWrapper')) of my target html element to put my table ... function createTableDynamically(){ var table = ""; for (var key in Object.keys(data[0])) { table += ""; } table += ""; for (var position in data) { table += "<tr company-id='" + data[position]['PublicCompanyId'] + "'>" for (var key in data[position]) { table += ""; } table += ""; } table += "
🌐
Cubewise
code.cubewise.com › blog › create-a-table-with-dynamic-columns
Create a table with dynamic columns
The second one <td ng-repeat=”version in page.versions”> will create one table column (td) per version in the “versions” set: <tbody> <tr ng-repeat="dept in page.depts"> <td>{{dept.description}}</td> <td ng-repeat="version in page.versions"> Define the cell </td> </tr> </tbody> The table structure is now defined, now we have to define what will be inside the table data.
🌐
JSFiddle
jsfiddle.net › Jaganathan › R2Her
Add Rows & Columns to a table dynamically - JSFiddle - Code Playground
Our CSS Flexbox generator lets you create a layout, and skip knowing the confusing properties and value names (let's be honest the W3C did not make a good job here).
Find elsewhere
🌐
SitePoint
sitepoint.com › html & css
Creating dynamic table - HTML & CSS - SitePoint Forums | Web Development & Design Community
January 4, 2016 - Hello, I need help to create dynamic table using data from database like this <table border="1"> <tr> <td>Coutry</td> <td>Position</td> <td>Name</td> </tr> <tr> <td rowspan="9">Usa<…
🌐
Madras Academy
madrasacademy.com › home › dynamic table generator using html, css, and javascript
Dynamic Table Generator Using HTML, CSS, and JavaScript - Madras Academy
March 15, 2025 - function generateTable() { let rows = document.getElementById('rows').value; let cols = document.getElementById('cols').value; let tableContainer = document.getElementById('table-container'); if (rows <= 0 || cols <= 0) { alert("Please enter ...
🌐
YouTube
youtube.com › watch
JavaScript Tips and Tricks 02 - build a dynamic html table - YouTube
Use JavaScript to build a dynamic html table using loops. This video discusses the structure of HTML tables and explains how to use the for loop to create th...
Published   February 11, 2016
🌐
Coderanch
coderanch.com › t › 457846 › languages › create-dynamic-rows-columns-HTML
How to create dynamic rows and columns in HTML tables (HTML Pages with CSS and JavaScript forum at Coderanch)
August 11, 2009 - <TR> tag creates row in a table and </TR> ends the row in html. similarly, <TD> creates a column and </TD> ends a column. You can use two for (or any other loops) to create rows and columns dynamically. For example, <tr> <td>column 1</td> <td>column2</td> </tr> will create 1 row and two columns.
🌐
Seldom India
seldomindia.com › create-dynamic-html-table-using-html-css-and-javascript
Create Dynamic HTML Table Using HTML, CSS and JavaScript. | Seldom India
September 28, 2024 - It retrieves the necessary elements from the HTML document, such as the table itself (myTable), the input fields for columns and rows, and the corresponding values entered by the user. 3. The function then clears any existing content in the table by removing all child elements. 4. Next, it creates the table header by dynamically generating th (table header) elements based on the number of columns specified. Each th element contains an input field with ...
🌐
JavaScript in Plain English
javascript.plainenglish.io › creating-a-dynamic-html-table-through-javascript-f554fba376cf
Creating a dynamic HTML table with JavaScript | by Daniel Scott Cole | JavaScript in Plain English
September 25, 2020 - This tutorial will teach you how to create a dynamic HTML table through the use of Javascript and Document Object Model (DOM) manipulation.
🌐
Mysamplecode
mysamplecode.com › 2012 › 04 › generate-html-table-using-javascript.html
Programmers Sample Guide: Dynamically generate HTML table using JavaScript - document.createElement() method
You can also create a table right from scratch using createElement method. <!DOCTYPE html> <html> <head> <title>HTML dynamic table using JavaScript</title> <script type="text/javascript" src="app.js"></script> </head> <body onload="load()"> ...
Top answer
1 of 5
1

You can use jQuery for this task and write a function that generates HTML with a dynamic value:

Complete Solution

<HTML>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript">
        function generateTable(number) {
            return "<table><tr><td>" + 
                   "<img src='C:/Users/User/Desktop/RE/G.JPG'></td></tr><tr><td align='center'>" +
                   number +
                   "</td></table>";
        }

        $(function(){
            var userInput = 3;

            for (var i = 0; i < userInput; i++) {
                $('#dynamic').append(generateTable(i + 1)); 
            }
        });
    </script>
</head>
<body>
    <div id='dynamic'></div>
</body>
</html>
2 of 5
1

You can add an input and a button to trigger the function. You could also check if the inserted value is actually a number or not.

$(document).on('click', '#add', function() {
  var that = $(this);
  var times = parseInt($('#times').val());
  for (i=1;i<=times;i++) {
    $('#table-wrp').append('<table class="table-times"><tbody><tr><td><img src="http://code52.org/aspnet-internationalization/icon.png" /></td></tr><tr><td>' + i + '</td></tr></tbody></table>');
  }
});

$(document).on('input', '#times', function() {
  var that = $(this);
  var value = that.val(); 
  if ((value != '' || value != false) && !isNaN(value)) {
    $('#add').prop('disabled', false);         
  } else {
    $('#add').prop('disabled', true);
  }      
});
#table-wrp {
  height: 80px;
}

.table-times {
  width: 100px;
  height: 80px;
  float: left;
  border-collapse: collapse;
}

.table-times td { 
   border: 1px solid #d8d8d8; 
   text-align: center;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="textbox" id="times" />
<button id="add" disabled>Add</button>
<div id="table-wrp"></div>

🌐
EncodedNA
encodedna.com › javascript › dynamically-add-remove-rows-to-html-table-using-javascript-and-save-data.htm
JavaScript: Add and Remove Rows Dynamically in HTML Table
Now, for developers who prefer working with vanilla JavaScript, this guide is for you. In this article, I'll show you step-by-step how to dynamically add and remove rows in an HTML table using plain JavaScript. No frameworks required. ... 1) How do you create an entire HTML table dynamically in JavaScript?
🌐
Bit Level Code
bitlevelcode.com › home › javascript › how to create dynamic html table using javascript
How to Create Dynamic HTML Table Using JavaScript
December 9, 2025 - The “Create a Table” button calls the tableCreate() function when clicked. ... The table is dynamically generated within a div with the dynamic-table class, making it easy to apply custom styles or additional functionality.