How to Dynamically Add Data to an HTML Table Using JavaScript?

Estimated read time 2 min read

Dynamically adding data to an HTML table using JavaScript can be done by manipulating the DOM elements of the table. Here’s an example using JavaScript and jQuery:

<!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <table id="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
    <script>
      function addRow() {
        let table = $("#table tbody");
        let row = $("<tr>");
        row.append($("<td>").text("John Doe"));
        row.append($("<td>").text(30));
        table.append(row);
      }

      addRow();
    </script>
  </body>
</html>

In this example, we first define an HTML table with a header and a body. The table body is empty, as we will dynamically add data to it using JavaScript.

We then define a JavaScript function called addRow that adds a row to the table. The function uses jQuery to select the table body, create a new row element, add data to the row, and finally append the row to the table body.

Finally, we call the addRow function to add a row to the table when the page loads.

Note that this example is just one way to dynamically add data to an HTML table using JavaScript. There are many other ways to do it, depending on your specific needs and the libraries and frameworks you are using.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply