Example: Creating a HTML table dynamically (Sample1.html)

by Ryan Brown

HTML

<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces -->


<form>
  Job Number:
  <br>
  <input type="text" name="jobN" id="jobN" value="168951-7">
  <br> Spool Size:
  <br>
  <input type="text" name="spoolS" id="spoolS" value="2500">
  <br> Spools:
  <br>
  <input type="text" name="number" id="number" value="5">
</form>
<input type="button" value="Generate a table." onclick="generate_table()">

JavaScript

function generate_table() {
  // get the reference for the body
  var body = document.getElementsByTagName("body")[0];
 
  // creates a <table> element and a <tbody> element
  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");
 
 var spools = document.getElementById("number").value;
  // creating all cells
  for (var i = 0; i < spools; i++) {
    // creates a table row
    var row = document.createElement("tr");
 
    for (var j = 0; j < 4; j++) {
      // Create a <td> element and a text node, make the text
      // node the contents of the <td>, and put the <td> at
      // the end of the table row
      
      
      var cell = document.createElement("td");
      var cellText = document.createTextNode("cell in row "+i+", column "+j);

      
      cell.appendChild(cellText);


    }
 
    // add the row to the end of the table body
    tblBody.appendChild(row);
  }
 
  // put the <tbody> in the <table>
  tbl.appendChild(tblBody);
  // appends <table> into <body>
  body.appendChild(tbl);
  // sets the border attribute of tbl to 2;
  tbl.setAttribute("border", "2");
}