You could iterate the array and build a new row if the remainder with 5 is zero.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    tr;

array.forEach((v, i) => {
    var td = document.createElement('td');
    
    if (!(i % 5)) {
        tr = document.createElement('tr');
        document.getElementById('table0').appendChild(tr);
    }
    td.appendChild(document.createTextNode(v));
    tr.appendChild(td);
});
<table id="table0"></table>

Answer from Nina Scholz on Stack Overflow
๐ŸŒ
Codedec
codedec.com โ€บ tutorials โ€บ how-to-create-dynamic-table-from-array-in-javascript
How To Create dynamic table from Array in JavaScript โ€“ CODEDEC
The innerHTML property is a property in JavaScript that allows the script to manipulates an HTML page by reading and writing data within a HTML tag. ... <!doctype html> <html> <head> <title>Create dynamic table from ArrayList using JavaScript</title> <style> .input{ border:none; font-size:10px; } .input:focus{ outline:none; } </style> </head> <body> <h2 style="text-align:left">Create dynamic table from ArrayList using JavaScript</h2> <table id="fetch" border="2" cellspacing="1" cellpadding="8" class="table"> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> <script type="text/javascript"> var array
Top answer
1 of 3
1

var arr = ["1","2","-3","4","-5","-6","7"];

var table = document.createElement("table"),          // create the table element
    tbody = document.createElement("tbody");          // create the table body element
    
table.appendChild(tbody);                             // add the table body to table

// ### POSITIVE ROW ######################

var tr = document.createElement("tr");                // create the table row element
arr.forEach(function(e) {                             // for each element e in arr
  var td = document.createElement("td");              // create a table cell element
  if(e >= 0) {                                        // if e is positive
    td.textContent = e;                               // then change the text content of this cell to e
    td.style.background = "#ccc";                     // and change the background as well
  }
  tr.appendChild(td);                                 // add the cell to the row (if the number is negative the cell will be empty and without background)
});
tbody.appendChild(tr);                                // add the row to table


//### NEGATIVE ROW ######################

tr = document.createElement("tr");                    // same but for negative numbers ...
arr.forEach(function(e) {
  var td = document.createElement("td");
  if(e < 0) {
    td.textContent = e;
    td.style.background = "#ccc";
  }
  tr.appendChild(td);
});
tbody.appendChild(tr);

document.body.appendChild(table);

You can group some of the code in a function and reuse it:

// elt is shortcut for document.createElement
function elt(tag) {
  return document.createElement(tag);
}

// take an array and a condition function conditionFN and return a row of all the element that passed the condition function with a background of #ccc
function makeRow(arr, conditionFN) {
  var tr = elt("tr");
  arr.forEach(function(e) {
    var td = elt("td");
    if (conditionFN(e)) {
      td.textContent = e;
      td.style.background = "#ccc";
    }
    tr.appendChild(td);
  });
  
  return tr;
}

// take an array and return the equivalent table element
function makeTable(arr) {
  var table = elt("table"),
      tbody = elt("tbody");

  table.appendChild(tbody);
  
  tbody.appendChild(makeRow(arr, function(e) { return e >= 0; })); // the condition function only allows positive numbers => positive row
  tbody.appendChild(makeRow(arr, function(e) { return e < 0; }));  // the condition function only allows negative numbers => negative row
  
  return table;
}



document.body.appendChild(makeTable([1, 2, -3, 4, -5, -6, -7, 8, 9, 10]));

2 of 3
0

Using recursive function and table.inertRow() and row.insertCell()

var data = ["1", "2", "-3", "4", "-5", "-6", "7"];
var table = document.getElementById('myTable')

function plusMinusRows(arr, rowNum) {      
  var row = table.insertRow();
  arr.map(Number).forEach(function(num) {
    var value = !rowNum  ? (num >= 0 ? num : '') : (num < 0 ? num : '');
    var cell = row.insertCell();
    cell.textContent = value;
    cell.style.background = value !== '' ? '#cccccc' : '';
  });
  // call function again when rowNum  not defined
  !rowNum && plusMinusRows(arr, 2);
}
// initialize 2 rows
plusMinusRows(data);
<table id="myTable"></table>

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 68514044 โ€บ jquery-dynamically-create-table-from-array
javascript - jquery dynamically create table from array - Stack Overflow
const exampleArray = [ { header: 'ID', values: [1, 2] }, { header: 'First Name', values: ['John', 'Jayne'] }, { header: 'Last Name', values: ['Doe', 'Doe'] } ]; const header = $('#results thead tr'); const body = $('#results tbody'); exampleArray.forEach((column) => { header.append( $(`<th>${column.header}</th>`) ); }); // Compute the number of rows in the array const nRows = exampleArray[0].values.length; for (let i = 0; i < nRows; i++) { // row contains all cells in a row let row = $("<tr/>"); // Loop over the columns exampleArray.forEach((column) => { // For each column, we add the i-th value, since we're building the i-th row row.append(`<td>${column.values[i]}</td>`); }); // Add the row to the table body body.append(row); }
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ javascript โ€บ javascript create table dynamically
How to Create Table Dynamically in JavaScript | Delft Stack
February 2, 2024 - var table = document.createElement('table'); var tr = document.createElement('tr'); var arrheader = ['ID', 'FirstName', 'LastName', 'Gender']; var array = [ {ID: 1, FirstName: 'Mehvish', LastName: 'Ashiq', Gender: 'Female'}, {ID: 2, FirstName: 'Thomas', LastName: 'Christoper', Gender: 'Male'}, {ID: 3, FirstName: 'Shiva', LastName: 'Pandy', Gender: 'Male'}, {ID: 4, FirstName: 'Tina', LastName: 'Robert', Gender: 'Female'} ]; for (var j = 0; j < array.length; j++) { var th = document.createElement('th'); // column var text = document.createTextNode(arrheader[j]); // cell th.appendChild(text); tr.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ API โ€บ Document_Object_Model โ€บ Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
Traversing an HTML table with JavaScript and DOM Interfaces
You can build this table and its internal child elements by using just a few DOM methods. Remember to keep in mind the tree model for the structures you are planning to create; this will make it easier to write the necessary code. In the <table> tree of Figure 1 the element <table> has one child: the element <tbody>. <tbody> has two children.
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ create-html-table-from-javascript-object
How to Create an HTML Table from a JavaScript Object Array (with Auto-Incrementing ID, Name & Relevance Columns) for Beginners โ€” javaspring.net
In this tutorial, weโ€™ll walk through creating a dynamic HTML table from a JavaScript object array. Weโ€™ll include **auto-incrementing IDs** (to uniquely identify each row), **Name**, and **Relevance** columns. By the end, youโ€™ll understand how to dynamically generate tables, manipulate ...
Find elsewhere
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 โ€บ 67340810 โ€บ dynamically-create-html-table-from-an-array
javascript - Dynamically create html table from an Array - Stack Overflow
<template> <table> <thead> <tr> <th v-for="(column, index) in columns" :key="index"> {{ column }} </th> </tr> </thead> <tbody> <tr v-for="(row, index) in rows" :key="index"> <td v-for="(column, index) in columns" :key="index"> {{ row[column] }} </td> </tr> </tbody> </table> </template> <script> export default { name: "Table", props: { columns: Array, rows: Array, }, }; </script> โ€ฆand the parent component would then pass the data into Table.vue like this: <template> <Table :columns="columns" :rows="rows" /> </template> <script> import Table from "./components/Table"; export default { name: "App", components: { Table, }, data() { return { columns: ["id", "title", "description"], rows: [ { id: 1, title: "what is this", description: "i like to describe", }, { id: 2, title: "wait wat?", description: "i like to describe, too", }, ], }; }, }; </script>
๐ŸŒ
GitHub
gist.github.com โ€บ etigui โ€บ 74980eed346a3dbed13f3c48ee4b1e8d
Creating HTML table dynamically using javascript ยท GitHub
Creating HTML table dynamically using javascript. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
Codepedia
codepedia.info โ€บ create-dynamic-html-table-using-jquery
Create Dynamic HTML Table from Array data [JQUERY] - Codepedia
August 24, 2021 - jQuery Add Dynamic Table with data in Array: Here in this article will explain how to create HTML table dynamically from the Array variable using jQuery. This means the columns, rows, and data get added dynamically to HTML table at runtime using jQuery. You can also check the previous article related jQuery table like How to remove table row tr in jQuery , Remove next row tr from a table in jQuery.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 50589783 โ€บ creating-table-with-javascript-and-dynamic-variables
arrays - Creating table with Javascript and dynamic variables - Stack Overflow
I am trying to make an application where you register a set of numbers, and then those numbers will be displayed in the table. I am able to register the first set of numbers, but if I change the numbers and press register again, i won't get a new row. Instead it updates the same row. Basically I am trying to make this program work in the way that pressing the register button will create a new row. window.onload = oppdater; function oppdater() { document.getElementById("btnRegistrer").onclick = registrer; } function registrer() { var arrayListe = []; var reg = {}; var verdi0 = parseInt(document
๐ŸŒ
Code Boxx
code-boxx.com โ€บ home โ€บ 2 ways to create table from array in javascript
2 Ways To Create Table From Array In Javascript
January 11, 2024 - This beginner's tutorial will show how to create table from array in Javascript using 2 different methods. Example code download included.
๐ŸŒ
ASPSnippets
aspsnippets.com โ€บ Articles โ€บ 906 โ€บ Create-dynamic-Table-in-HTML-at-runtime-using-JavaScript
Create dynamic Table in HTML at runtime using JavaScript
February 26, 2019 - A loop is executed over the array elements and one by one a Row is created in the HTML Table. Then inside each Row a Cell is added using the Table ... Table Row insertCell Method: This method adds a new cell to a Table Row at the specified index.
Top answer
1 of 2
2

1) This my answer how do this on VueJS and jQuery

2) Vanilla js - CODEPEN - DEMO

// Get DOM elements
const $el = [
    '#tmpl',
    '#user-count',
    '#people-count',
    '#form-items',
    '#btn-add',
    '#form',
].reduce((res, item) => {
    const method = item.startsWith('#')
        ? 'querySelector'
        : 'querySelectorAll'
    const key = item
        .replace(/\W/ig, ' ').trim()
        .replace(/\s+\w/g, v => v.trim().toUpperCase())
    res[key] = documentmethod
    return res
}, {})

// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()

// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
    const peopleCount = +$el.peopleCount.value
    const html = Array(peopleCount)
            .fill(tmpl)
            .join('')
    $el.formItems.insertAdjacentHTML('beforeend', html)
})

// Submit form
$el.form.addEventListener('submit', e => {
    e.preventDefault()
    alert('Submit form by ajax or remove this method for default behavior')
})

// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
    // Delete behaviors
    if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
        e.target.closest('.row').remove()
    }
})
<div id="app">
    <div>
        <div>
            <button id="btn-add">Add new user</button>
            <label>Number of People:</label>
            <input type="number" id="people-count" value="1" min="1">
        </div>
        <form id="form">
            <div id="form-items" data-empty="Users list is empty"></div>
            <button>Send</button>
        </form>
    </div>
</div>

<script type="text/x-template" id="tmpl">
    <div class="row">
        <label>
            Name:
            <input class="people" name="name[]">
        </label>
        <label>
            Surname:
            <input class="people" name="surname[]">
        </label>
        <label>
            Email:
            <input type="email" class="people" name="email[]">
        </label>
        <button class="btn-del">Delete</button>
    </div>
</script>

<style>
    .people {
        width: 80px;
    }
    #form-items:empty + button {
        display: none;
    }
    #form-items:empty:before {
        content: attr(data-empty);
        display: block;
    }
</style>

2 of 2
1

I have edited your code,

function createInputTable() 
    {
    var num_rows = document.getElementById('rows').value;
    var tableName = document.getElementById('conn_input_device').value;
    var column_number = 2;
    var tdefine = '<form id="form"><table id="table" border = "1">\n';
    var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
    var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
    var tbody = '';
    var tfooter = '</table>';
    var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
    var i = 0;                  

    for (var i= 0; i < num_rows; i++)
      {
      tbody += '<tr><td>' + (i+1)  + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
      tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
      }
      document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
      
    }
    
    
    function formData()
    {
        var cellData = document.getElementsByTagName("tr");
        var obj = [];
        for(var i=0;i<cellData.length-1;i++){
          obj.push(document.getElementById("i"+i).value);
          obj.push(document.getElementById("o"+i).value);
        }
        alert(JSON.stringify(obj));
       
    }
<form id="tableGen" name="table_gen">
        <label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
        <label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
        <input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
    </form>

    
    <div id="wrapper"></div>

๐ŸŒ
Medium
medium.com โ€บ wdstack โ€บ quick-blurb-generating-a-table-from-an-array-in-javascript-41386fd449a9
Quick Blurb: Generating a Table from an Array in JavaScript | by Zak Frisch | WDstack | Medium
January 24, 2017 - //setup our table array var tableArr = [ ["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"] ]//create a Table Object let table = document.createElement('table');//iterate over every array(row) within tableArr for (let row of tableArr) {//Insert a new row element into the table element table.insertRow();//Iterate over every index(cell) in each array(row) for (let cell of row) {//While iterating over the index(cell) //insert a cell into the table element let newCell = table.rows[table.rows.length - 1].insertCell();//add text to the created cell element newCell.textContent = cell; } }//append the compiled table to the DOM document.body.appendChild(table);
๐ŸŒ
Mysamplecode
mysamplecode.com โ€บ 2012 โ€บ 04 โ€บ generate-html-table-using-javascript.html
Programmers Sample Guide: Dynamically generate HTML table using JavaScript - document.createElement() method
function addRow() { var myName = document.getElementById("name"); var age = document.getElementById("age"); var table = document.getElementById("myTableData"); var rowCount = table.rows.length; var row = table.insertRow(rowCount); ...