Reputation: 463
I dynamically add data to table from a Javascript object. I have a code that ends up something like this:
<table>
<tr>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
I want table borders in each row even if the tds don't exist. So basically for the example in the code I want a 3x3 table with borders. Is this possible without actually making empty tds in each row?
Upvotes: 4
Views: 1722
Reputation: 10976
You can:
colspan
attributes (<td colspan="3">
will be as wide as 3 <td>
's; Of course you will lose the grid symmetry.var table = document.getElementsByTagName('table')[0];
function normalizeTable() {
var trs = table.getElementsByTagName('tr'),
len = trs.length, max = 0, td;
// first we search for the longest table row in terms of # of children
for (var i = len; i--;) {
if (trs[i].children.length > max)
max = trs[i].children.length;
}
// now we can fill the other rows
for (var j = len; j--;) {
while (trs[j].children.length < max) {
td = document.createElement('td');
trs[j].appendChild(td);
}
}
}
normalizeTable();
Upvotes: 1
Reputation: 696
EDITED
In my opinion, you have to add only a little CSS and insert all TD (empty):
table {
border-style: solid;
border-width: 1px;
border-collapse: separate;
empty-cells: show;
}
td {
border-style: solid;
border-width: 1px;
}
<table>
<tr>
<td>1</td>
<td></td> <!-- empty -->
<td></td> <!-- empty -->
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td></td> <!-- empty -->
</tr>
</table>
Upvotes: 0