Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

how to dynamically add rows to table using html, css and javascript


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. 

Prerequisite

Basic knowledge of Html, CSS and JavaScript are required to fully understand the content of this post.

Html

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>

CSS

Now we style the table

#table-container {
max-width400px;
padding5px;
margin0 auto;
}
#main-table {
width100%;
colorwhite;
}
#main-table th {
background#27afd8;
padding7px;
}
#main-table td {
background#4a9eb8;
text-aligncenter;
padding7px;
}

#table-container button {
floatright;
bordernone;
padding5px 12px;
margin10px 0;
background#27afd8;
colorwhite;
cursorpointer;
}

JavaScript

Now we have to code the addRow() function that adds the rows dynamically.

//Adds a click listener to the add-row button
document.querySelector("#add-row").addEventListener("click", () => {
//calls the addRow() method on clicking the button
addRow();
});

//initializing the row counter
let x = 2;

const addRow = () => {
//creates a new row element
let row = document.createElement("tr");

//creates a new column element
let column1 = document.createElement("td");

//create text for the column element
const column1text = document.createTextNode(`Row ${x} Column 1`);

//appends the text to the column element
column1.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 row
row.appendChild(column1);

//appends the second column to the new row
row.appendChild(column2);

//appends the row to the table
document.querySelector("#main-table").appendChild(row);
x++;
};

Conclusion

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