CellPadding not working for table?

John picture John · Nov 25, 2014 · Viewed 11.8k times · Source

Using DOM elements trying to add cellPadding to a table: why does

var FirstTabContent = document.createElement('div');
var Newtable = document.createElement('table');
Newtable.border = "1";
Newtable.cellpadding = "20px 20px 20px 20px";
///////////////
//populate table
///////////////
FirstTabContent.appendChild(Newtable);
return FirstTabContent.innerHTML;

return:

<table border="1">
   <tbody>
      <tr>
         <td>
            <b>id</b>
         </td>
         <td>14079<br>
         </td>
      </tr>
   </tbody>
</table>

where is the cellpadding?

Answer

BoltClock picture BoltClock · Nov 25, 2014

Strictly speaking, cellPadding (with a capital P) corresponds to the cellpadding presentational attribute on the table element itself, which only accepts a single length or percentage:

Newtable.cellPadding = "20";

But if you're trying to apply cell padding to this generated table via CSS (as implied by the 20px 20px 20px 20px value), you should use CSS, and with CSS, you need to set it on the td elements and not the table:

td {
    padding: 20px;
}

Otherwise you will need to loop through all the cells in the table (once you add them) and set style.padding on them, which is just plain tedious.

If you really want to use the cellPadding property, note that you can only set a uniform padding this way if you use a pixel value, since it only accepts a single value.