How to Dynamically Add Rows in HTML table using JavaScript?

Are you having trouble adding rows to an HTML table dynamically using JavaScript?

Worry no more because, in this article, we will walk you through the whole process of how to do it.

So bear with us as this article explore how to add rows dynamically to a table using JavaScript.

At the end of this tutorial, you’ll be able to have a solid understanding of how to use JavaScript to add rows to a table effortlessly and effectively.

Understanding the JavaScript Add Row to Table

Before we get into the solutions, let’s first understand the basics of what we want to do.

When we say “adding rows to a table dynamically,” it simply means we can insert new data into the table without having to refresh the whole page.

It is helpful when we have to change data or want to make things more user-friendly.

How to add rows to a table using JavaScript DOM?

Here’s the solution for adding rows to a table using JavaScript DOM.

Using the insertRow() method

You can use JavaScript to add new rows to an HTML table as needed.

To do this, you can use the insertRow() method, which lets you add a new row at a particular position within the table.

Syntax

table.insertCell(index)

Here’s a simple code example that shows how to add a new row to a table with the ID “sampleTable” when a button is clicked.

<!DOCTYPE html>
<html>
<head>
   <title> Adding rows to a table using JavaScript DOM </title>
   <style>
      table,
      td,
      th {
         border: 1px solid black;
      }
      body {
         background-color: lightblue;
         text-align: center;
      }
      #myTable {
         margin: 0 auto;
      }
   </style>
</head>
<body>
   <h2> Adding rows to a table using JavaScript DOM </h2>  

   <table id="sampleTable">
      <thead>
         <th> Name </th>
         <th> Age </th>
         <th> Gender </th>
         <th> Email </th>


      </thead>
      <tbody>
         <tr>
            <td> It Sourcecode </td>
            <td> 18 </td>
            <td> Male </td>
            <td> [email protected] </td>
         </tr>
         <tr>
           <td> Caren </td>
            <td> 18 </td>
            <td> Female </td>
            <td> [email protected] </td>
         </tr>
         <tr>
            <td> Glay</td>
            <td> 18 </td>
            <td> Female </td>
            <td> [email protected] </td>
         </tr>
            <tr>
            <td> Donz</td>
            <td> 18 </td>
            <td> Male </td>
            <td> [email protected] </td>
         </tr>

      </tbody>
   </table>

   <br>

   <p style="text-align:center;"> Try to click the "Add" button to add the row to the table </p>

   <div style="text-align:center;">
     <button id="btn" onclick="addRow()"> Add </button>
   </div>

<script>

   function addRow() {
      // Get the table element in which you want to add row
      let table = document.getElementById("myTable");
   
      // Create a row using the inserRow() method and
      // specify the index where you want to add the row

      let row = table.insertRow(-1); // We are adding at the end ✅
   
      // Create table cells
      let c1 = row.insertCell(0);
      let c2 = row.insertCell(1);
      let c3 = row.insertCell(2);
      let c4 = row.insertCell(3);
   
      // Add data to c1 and c2
      c1.innerText = "Sample"
      c2.innerText = 18
      c3.innerText = "sample"
      c4.innerText = "[email protected]"
   }

</script>

</body>

</html>

Output:

A step-by-step guide on how to add and remove rows to a table using JavaScript

Here’s the step-by-step guide for adding and removing rows to a table using JavaScript.

1. Set up the HTML Structure

To start, you will require an HTML table that will act as the container for our dynamically added rows.

Let’s begin by creating a basic HTML table as our initial setup.

<table id="dynamic-table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Gender</th>
     <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <!-- Dynamic rows will be inserted here -->
  </tbody>
</table>

Output:

NameAgeGenderEmail

2. Access the table

After we set up the HTML Structure , we must utilize JavaScript to access the table element. To accomplish this, we will use the document.getElementById() method.

const table = document.getElementById('dynamic-table');

3. Create a new row

Then, we will create a function that adds a new row to the table when called.

Let’s name it addRow():

function addRow() {
const newRow = table.insertRow();
}

4. Add Cells to the Row

Now, we have a new row, we just need to add cells (table data) to it. We will use the insertCell() method:

function addRow() {
const newRow = table.insertRow();
const nameCell = newRow.insertCell();
const ageCell = newRow.insertCell();
const genderCell = newRow.insertCell();
const emailCell = newRow.insertCell();

}

5. Populate its cells with data

To ensure the new row contains relevant information, we need to populate its cells with data.

For illustration purposes, we will use sample data in this demonstration.

However, in a real-world scenario, you would retrieve data dynamically from a data source.

function addRow() {
const newRow = table.insertRow();
const nameCell = newRow.insertCell();
const ageCell = newRow.insertCell();
const genderCell = newRow.insertCell();
const emailCell = newRow.insertCell();


nameCell.innerHTML = "Itsourcecode";
ageCell.innerHTML = '18';
genderCell.innerHTML = '18';
emailCell.innerHTML = "[email protected]";
}

6. Call the function

Lastly, we need to trigger the addRow() function to see the result. You can call this function in response to a button click or any other event:

const addButton = document.getElementById('add-button');
addButton.addEventListener('click', addRow);

With this implementation, whenever the user clicks the element with the ID “add-button,” a new row with sample data will be added to the table dynamically.

Here’s the complete code:

<!DOCTYPE html>
<html>
<head>
  <title>Dynamic Table - JavaScript</title>
  <style>
    /* Center the table and buttons */
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100vh;
      margin: 0;
    }
    #dynamic-table, #add-button, #remove-button {
      display: block;
      margin: 0 auto;
    }
  </style>
</head>
<body>
  <table id="dynamic-table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <!-- Dynamic rows will be inserted here -->
    </tbody>
  </table>

  <button id="add-button">Add Row</button>
  <button id="remove-button">Remove Last Row</button>

  <script>
    const table = document.getElementById('dynamic-table');
    const addButton = document.getElementById('add-button');
    const removeButton = document.getElementById('remove-button');

    addButton.addEventListener('click', addRow);
    removeButton.addEventListener('click', removeRow);

    function addRow() {
      const newRow = table.insertRow();
      const nameCell = newRow.insertCell();
      const ageCell = newRow.insertCell();
      const genderCell = newRow.insertCell();
      const emailCell = newRow.insertCell();

      nameCell.innerHTML = "Itsourcecode";
      ageCell.innerHTML = '18';
      genderCell.innerHTML = 'Male';
      emailCell.innerHTML = "[email protected]";
    }

    function removeRow() {
      const rows = table.getElementsByTagName('tr');
      if (rows.length > 1) {
        table.deleteRow(rows.length - 1);
      }
    }
  </script>
</body>
</html>

Output:

Conclusion

In conclusion, this article provided solutions on how to add rows dynamically to an HTML table using JavaScript.

The main focus was on using the insertRow() method to achieve this functionality.

By inserting rows at a specified position within the table, developers can add new data to the table without the need to refresh the entire page, making the user experience more seamless and user-friendly.

We also have an example of adding and removing a new row to a sample table when a button is clicked. 

The JavaScript code demonstrated how to create a new row and insert cells with sample data into the table.

We are hoping that this article provides you with enough information that helps you understand the JavaScript add row to table.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment