Insert, Delete Rows, columns in HTML table Using Javascript
How to insert delete rows and cells dynamically in table using JavaScript
Lets create a table objectvar table=document.CreateElement('table');
Or if you want to modify existing table then use below line.
var table=document.getElementById('empTable');
you can set the attributes of table object using following code
//Syntax object.setAttribute(attributeName, attributeValue);
table.setAttribute("cellpadding","0");
table.setAttribute("cellspacing","0");
Now i want to add new row at the end, table, For this you need to get the Count of rows in table and Add the row at last index.
var rows=table.getElementsByTagName('tr');
this will return the rows as array of object.
Now insert new row at last index of table
var lastIndex=rows.length;
var newRow=table.insertRow(lastIndex);
Now add the column to the newRow object.
var cell=newRow.incertCell(0);
Lets say i want to set inner HTML of this cell to employ name
cell.innerHTML="Peter";
Align the text to left of cell
cell.setAttribute("align","left");
Now I want to add other address column to row.
var cellAddress=newRow.InsertCell(1);
cellAddress.innerHTML="address of the employe";
cellAddress.SetAttribute("align","Align");
Now you have understand how to add new rows and column to HTML table.
Now how to remove the rows and column.
Lets say if want to remove address column from 5th row
var rows=table.getElementsByTagName('tr');
var row5=rows[5];
row5.removeCell(1);
it will remove the second column means address column from employ table.
or if you want to remove 5 rows the use
table.removeRow(row5);
Comments
Post a Comment