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.

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

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>
  <style>
    table, th, td { border: solid 1px #ddd; border-collapse: collapse;
      padding: 2px 3px; text-align: center; margin: 10px 0; }
    th { font-weight:bold; }
    input { margin: 10px; cursor: pointer; }
  </style>
</head>

<body> 
  <!--dynamically created elements with be show here.-->
</body>

<script>
  let create_table = () => {
    const table = document.createElement('table');  // create a table

    // Set table id. We need the id to travese and extract data from the table.
    table.setAttribute('id', 'empTable');
    let tr = table.insertRow(-1);

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

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

    arrHead.forEach ((item) => {
      let th = document.createElement('th');  // table header.
      th.innerHTML = item;
      tr.appendChild(th);
    });

    arrValue.forEach ((ele) => {
      tr = table.insertRow(-1);
      
      let val = Object.values(ele);
      
      val.forEach ((item) => {
        let td = document.createElement('td'); // table definition.
        td = tr.insertCell(-1);
        td.innerHTML = item;	// add values to each cell.
      });
    });
    
    // Now, create a button and set attributes 'type', 'value' and click event.
    let button = document.createElement('input');
    button.setAttribute('type', 'button');
    button.setAttribute('value', 'Read Table Data');
    button.setAttribute('onclick', 'getTableValues()');  // call a function on click event.

    // Finally, add the table and button elements to the body.
    document.body
      .appendChild(table)
    	.appendChild(button);
  }

  let getTableValues = () => {
    let empTable = document.getElementById('empTable');

    // Create a DIV element where you'll show the table.
    var div = document.createElement('div');
    div.innerHTML = "";
    div.innerHTML = '<br />';
    
    let rows = Array.from(empTable.rows).slice(1);	// ignore the 1st row.
    
    // traverse each table row and get cell values.
    Array.from(rows).forEach((row) => { 
      let rowValues = []; 
      Array.from(row.cells).forEach((cell) => { 
        div.innerHTML = div.innerHTML + ' ' + cell.innerHTML; // add data
      }); 
      
      div.innerHTML = div.innerHTML + '<br />';
    });
    
    // append the DIV (with data) to the body.
    document.body.appendChild(div);
  }
  
  create_table(); 
</script>
</html>
Try it

I dynamically created every element in this example form using the document.createElement() method. This method is incredibly powerful and versatile, allowing you to create any number of elements as needed. Plus, it's quick and efficient.

You can experiment with the document.createElement() method to create various elements. For instance, instead of using an input type button (<input>), you can create and add an HTML <button> tag. Here's how you do it

let button = document.createElement('button');          // CREATE THE BUTTON.
let 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 remains the same.

See this demo

Why would you create dynamic elements, is upto you. 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.

← PreviousNext →