AlesSvetina
AlesSvetina

Reputation: 463

Add empty td to rows which have less tds than max

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

Answers (2)

webketje
webketje

Reputation: 10976

You can:

  • Modify the original JS so that it generates colspan attributes (<td colspan="3"> will be as wide as 3 <td>'s; Of course you will lose the grid symmetry.
  • If your table cells each have the same fixed width, you could use a background-image on the table.
  • You could wrap up a little script to complete the table, cf:
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

Giacomo Alessandroni
Giacomo Alessandroni

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

Related Questions