Dynamic Table | |
---|---|
Row 1 Column 1 | Row 1 Column 2 |
In this tutorial, we will learn how to create a dynamic table that dynamically adds a row on clicking on the Add Row button.
Basic knowledge of Html, CSS and JavaScript are required to fully understand the content of this post.
First, we have to create the initial table that you see when you first load the page using Html
<div id="table-container"><table id="main-table" cellspacing="0"><th colspan="2">Dynamic Table</th><tr><td>Row 1 Column 1</td><td>Row 1 Column 2</td></tr></table><button id="add-row">Add Row</button></div>
Now we style the table
#table-container {max-width: 400px;padding: 5px;margin: 0 auto;}#main-table {width: 100%;color: white;}#main-table th {background: #27afd8;padding: 7px;}#main-table td {background: #4a9eb8;text-align: center;padding: 7px;}#table-container button {float: right;border: none;padding: 5px 12px;margin: 10px 0;background: #27afd8;color: white;cursor: pointer;}
Now we have to code the addRow() function that adds the rows dynamically.
//Adds a click listener to the add-row buttondocument.querySelector("#add-row").addEventListener("click", () => {//calls the addRow() method on clicking the buttonaddRow();});//initializing the row counterlet x = 2;const addRow = () => {//creates a new row elementlet row = document.createElement("tr");//creates a new column elementlet column1 = document.createElement("td");//create text for the column elementconst column1text = document.createTextNode(`Row ${x} Column 1`);//appends the text to the column elementcolumn1.appendChild(column1text);let column2 = document.createElement("td");const column2text = document.createTextNode(`Row ${x} Column 2`);column2.appendChild(column2text);//appends the first column to the new rowrow.appendChild(column1);//appends the second column to the new rowrow.appendChild(column2);//appends the row to the tabledocument.querySelector("#main-table").appendChild(row);x++;};
knowing how to load elements dynamically is very important especially when loading content from a server or collecting information randomly from users. Hope you enjoyed the tutorials, see you in the next