Dynamically generate HTML table using JavaScript - document.createElement() method

This tutorial covers the following topics
  • Create a Row dynamically inside the table from form data
  • Add a Delete button to the added table Row
  • Ability to delete the dynamically generated table Row

Generate HTML table dynamically using JavaScript
Generate HTML table dynamically using JavaScript
Generate HTML table dynamically using JavaScript
We have created a simple HTML form with name and age input. When the user clicks on the Add button we add a row to the Table element dynamically. You can also create a table right from scratch using createElement method.

Source for the HTML page - index.html

<!DOCTYPE html>
    <title>HTML dynamic table using JavaScript</title>
    <script type="text/javascript" src="app.js"></script>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
        <td><input type="text" id="name"></td>
        <td><input type="text" id="age">
        <input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
<div id="mydata">
<b>Current data in the system ...</b>
<table id="myTableData"  border="1" cellpadding="2">
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript

Source for the JavaScript file - app.js

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);

    row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
    row.insertCell(1).innerHTML= myName.value;
    row.insertCell(2).innerHTML= age.value;


function deleteRow(obj) {
    var index = obj.parentNode.parentNode.rowIndex;
    var table = document.getElementById("myTableData");

function addTable() {
    var myTableDiv = document.getElementById("myDynamicTable");
    var table = document.createElement('TABLE');
    var tableBody = document.createElement('TBODY');
    for (var i=0; i<3; i++){
       var tr = document.createElement('TR');
       for (var j=0; j<4; j++){
           var td = document.createElement('TD');
           td.appendChild(document.createTextNode("Cell " + i + "," + j));

function load() {
    console.log("Page load finished");


1 comment:

john said...

The addTable creates duplicates values I need to display 88 values and be able to click on one of them and see the value on the monitor

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.