I have a table where I want to insert a new row with a different colspan then the original table. Here is part of my code:
var table = document.getElementById("eTable");
var rowIndex = document.getElementById(ID).rowIndex;
var row = table.insertRow(rowIndex + 1);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
My original table has 5 columns, but I want to merge cell1,cell2, and cell3. How do I do that?
I have a table where I want to insert a new row with a different colspan then the original table. Here is part of my code:
var table = document.getElementById("eTable");
var rowIndex = document.getElementById(ID).rowIndex;
var row = table.insertRow(rowIndex + 1);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
My original table has 5 columns, but I want to merge cell1,cell2, and cell3. How do I do that?
Share Improve this question edited Nov 23, 2018 at 13:20 barbsan 3,46811 gold badges23 silver badges29 bronze badges asked Nov 23, 2018 at 13:14 TheAskerTheAsker 551 silver badge9 bronze badges 4-
"row with a different colspan" There's no such a thing in HTMLTables,
rowspan
andcolspan
are properties oftd
elements. But you can merge the cells. Addcell.colspan = 3;
and omitcell3
andcell4
. – Teemu Commented Nov 23, 2018 at 13:19 - how would you do that ? – TheAsker Commented Nov 23, 2018 at 13:25
- ??How?? Exactly like in my ment ... – Teemu Commented Nov 23, 2018 at 13:29
-
@TheAsker build table using string like
var tableBuild = '<table>
//loop your data here as required with col or rowspan` </table>'` . Refer this solution stackoverflow./a/8749347/4425004 – Pranesh Janarthanan Commented Nov 23, 2018 at 13:35
2 Answers
Reset to default 5It's possible to set the colspan for a column and skip some other columns. Based on your code (added second row):
var table = document.getElementById("eTable");
var rowIndex = document.getElementById("ID").rowIndex;
var row = table.insertRow(rowIndex + 1);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
row = table.insertRow(rowIndex);
cell = row.insertCell(0);
cell1 = row.insertCell(1);
cell1.colSpan = "3";
cell2 = row.insertCell(2);
table { border: 1px solid #000; width: 100%; }
table tr { }
table td { border: 1px solid red; height: 20px;}
<input type="hidden" id="ID" value=0 />
<table id="eTable">
</table>
Run the snippet or if you prefer, see this fiddle
Try below javascript code.
var cell2 = row.insertCell(2);
cell2.id = "myTd";
document.getElementById("myTd").colSpan = "3"