Dynamically create a table, button and DIV in JavaScript

← PrevNext →

With document.createElement() method you can create a specified HTML element dynamically in JavaScript. Once created, you can insert (or add) the element to your web page, or add it to a pre-defined element or a dynamically created element. In fact, you can create an entire form dynamically using this method. In this article, I’ll show you how to create an HTML table dynamically using the “createElement()” method and populate the table with data extracted from an array.

JavaScript createElement() Method

A form usually contains not just a table, but other elements too. For example, we will need a button to extract the data from the table and submit it. Therefore, along with a <table>, I’ll also show you how to create an Input type button element along with DIV element (will serve as a container) using the createElement() method.

That is, using the method we’ll actually create three elements, dynamically in this example.

Finally, I’ll show you how to traverse through the dynamically created table to extract all the values from each cell and submit the values.

See this demo

Why would you do this, would depend on your choice. It’s your decision to either add all the elements on the page while designing or you can create and insert HTML elements at runtime, that is dynamically using the createElement() method.

Also Read: How to Read Data from an HTML Table using JavaScript

So, let’s begin with our example.

The Markup with the Script

I am not adding any control at design time. Therefore, there is not much in the markup section. All the elements I’ll create and add at runtime in JavaScript.

The body onload event calls a JavaScript function called CreateTable().

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript document.createElement Method Example</title>
    <style>
        table, th, td 
        {
            font: 17px Calibri;
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
            margin: 10px 0;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body onload="CreateTable();">
    
</body>

<script>
    function CreateTable() {

        // CREATE DYNAMIC TABLE.
        var table = document.createElement('table');

        // SET THE TABLE ID. 
        // WE WOULD NEED THE ID TO TRAVERSE AND EXTRACT DATA FROM THE TABLE.
        table.setAttribute('id', 'empTable');

        var arrHead = new Array();
        arrHead = ['Emp. ID', 'Emp.Name', 'Designation'];

        var arrValue = new Array();
        arrValue.push(['1', 'Green Field', 'Accountant']);
        arrValue.push(['2', 'Arun Banik', 'Project Manager']);
        arrValue.push(['3', 'Dewane Paul', 'Programmer']);

        var tr = table.insertRow(-1);

        for (var h = 0; h < arrHead.length; h++) {
            var th = document.createElement('th');              // TABLE HEADER.
            th.innerHTML = arrHead[h];
            tr.appendChild(th);
        }

        for (var c = 0; c <= arrValue.length - 1; c++) {
            tr = table.insertRow(-1);

            for (var j = 0; j < arrHead.length; j++) {
                var td = document.createElement('td');          // TABLE DEFINITION.
                td = tr.insertCell(-1);
                td.innerHTML = arrValue[c][j];                  // ADD VALUES TO EACH CELL.
            }
        }

        // NOW CREATE AN INPUT BOX TYPE BUTTON USING createElement() METHOD.
        var button = document.createElement('input');

        // SET INPUT ATTRIBUTE 'type' AND 'value'.
        button.setAttribute('type', 'button');
        button.setAttribute('value', 'Read Table Data');

        // ADD THE BUTTON's 'onclick' EVENT.
        button.setAttribute('onclick', 'GetTableValues()');

        // FINALLY ADD THE NEWLY CREATED TABLE AND BUTTON TO THE BODY.
        document.body.appendChild(table);
        document.body.appendChild(button);
    }

    function GetTableValues() {

        var empTable = document.getElementById('empTable');

        // CREATE A DIV WHERE WE'LL SHOW THE TABLE WITH DATA.
        var div = document.createElement('div');
        div.innerHTML = "";
        div.innerHTML = '<br />';

        // TRAVERSE THROUGH THE TABLE TO XTRACT CELL VALUES.
        for (var r = 1; r <= empTable.rows.length - 1; r++) {        // EACH ROW IN THE TABLE.
            // EACH CELL IN A ROW.
            for (c = 0; c <= empTable.rows[r].cells.length - 1; c++) {      

                // ADD DATA TO THE DIV.
                div.innerHTML = div.innerHTML + ' ' +
                       empTable.rows[r].cells[c].innerHTML;

            }
            div.innerHTML = div.innerHTML + '<br />';
        }
        document.body.appendChild(div);     // APPEND (ADD) THE CONTAINER TO THE BODY.
    }
</script>
</html>
Try it

I have created every element in this example form dynamically using the document.createElement() method. So, I know how powerful and useful the method is and you can create any number of elements according to your requirement. And its quick.

Related: Add Rows to a Table Dynamically using jQuery

You can experiment with the method and create other elements too. For example, instead of Input type button (<input>), you can create and add HTML <button> tag. This is how you do it.

var button = document.createElement('button');          // CREATE THE BUTTON.
var bText = document.createTextNode('Submit');          // CREATE TEXT FOR THE BUTTON
button.appendChild(bText);                              // ADD THE TEXT TO THE BUTTON.

Once you have created the <button> tag, add the onclick event attribute to the button.

button.setAttribute('onclick', 'GetTableValues()');

Everything else will remain the same.

See this demo

← PreviousNext →