JavaScript function to add Rows to a Table

← PrevNext →

Ok, lets write a simple JavaScript function to add new rows to an HTML table.

You can use the insertRow() method in JavaScript to create an empty <tr> element (or tag) and insert it into a table. For example,

let tr = myTable.insertRow(row_count);

Now let’s see the complete script.

First, the Markup

Let us assume, I have an HTML table with only "headers". With every click of a button, the script should create a new row and add it to the table.

<!DOCTYPE html>
<html>
<head>
  <style>
    <!--table style-->
    table { width: 100%; }
    table, th, td { 
      border: solid 1px #DDD;
      border-collapse: collapse; 
      padding: 2px 3px; 
      text-align: center;
    }
  </style>
</head>
<body>
  <p>
    <input type="button" id="bt" value="Add row" onclick="addRow()" />
  </p>

  <div id="container">
    <!--the table with only headers-->
    <table id='tab'>
      <tr>
        <th></th>
        <th>Header 1</th>
        <th>Header 2</th>
        <th>Header 3</th>
      </tr>
    </table>
  </div>
</body>

The JS Script to add Rows to Table

Now, here's the JavaScript function to add new rows to an HTML table.

<script>
  let iCnt = 1;

  // Function to add new rows to table.
  let addRow = () => {
    let myTable = document.getElementById('tab');

    let rowCnt = myTable.rows.length;   // table row count.
    let tr = myTable.insertRow(rowCnt);   // the table row.

    let headCount = myTable.rows[0].getElementsByTagName('th').length;	// get header count.

    for (let c = 0; c < headCount; c++) {
      let td = document.createElement('td');    // table definition.
      td = tr.insertCell(c);

      if (c === 0) {      // the first column.
        // Show serial number.
        let span = document.createElement('span');

        // set input attributes.
        span.innerHTML = iCnt;
        td.appendChild(span);
      }
      else {
        // 2nd, 3rd and 4th column, will have textbox.
        let ele = document.createElement('input');
        ele.setAttribute('type', 'text');
        ele.setAttribute('value', '');

        td.appendChild(ele);
      }
    }
    
    iCnt += 1;
  }
</script>
</html>
Try it

Every row the script creates, each cell in the row has a textbox (or an input box). So, you can enter any text into the input box and save the data.

Note: The above script does not read or save data anywhere. You can check this example if you want to add more functionalities to the script.

← PreviousNext →