In this article i am going to show you How to dynamically add or remove(delete) rows from table using Javascript
Consider you have following html
We already have a table with id = "my-table"
first let's create rows
var row1 = table.insertRow(0);
Above command creates an empty <tr> element and adds it to the first position of the table
var row2 = table.insertRow(1);
Above command creates an empty <tr> element and adds it to the second position of the table
Now, let's create row cells
var cell1 = row1.insertCell(0);
cell1.innerHTML = "Name";
Above command creates an empty cell and adds it to first row of the table
var cell2 = document.createElement("td");
cell2.innerHTML = "Age";
Above command creates an empty cell and adds it to first row of the table.
Now we have a table with two rows and first row having two cells.
Consider you have following html
<html>
<body>
<div id="table-container">
<table id="my-table">
</table>
</div>
</body>
</html>
We already have a table with id = "my-table"
Now, let's see how to add rows dynamically using Javascript
first let's create rows
var row1 = table.insertRow(0);
Above command creates an empty <tr> element and adds it to the first position of the table
var row2 = table.insertRow(1);
Above command creates an empty <tr> element and adds it to the second position of the table
Now, let's create row cells
var cell1 = row1.insertCell(0);
cell1.innerHTML = "Name";
Above command creates an empty cell and adds it to first row of the table
var cell2 = document.createElement("td");
cell2.innerHTML = "Age";
Above command creates an empty cell and adds it to first row of the table.
Now we have a table with two rows and first row having two cells.
Remove rows dynamically using Javascript
document.getElementById("my-table").deleteRow(0);
Above command deletes first row from the table having id = "my-table"
In this way we can dynamically add or delete rows from table dynamically JavaScript
Also check - Create table dynamically using JQuery
No comments:
Post a Comment