CellPadding not working for table?

14.5k views Asked by At

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?

2

There are 2 answers

0
BoltClock On

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.

0
Salman A On

It should be cellPadding with an upper case P.

Setting Newtable.cellPadding = "20px 20px 20px 20px" might set the attribute to desired value but it will not produce the desired result. You can only set it to a pixel or a percentage length:

Newtable.cellPadding = "20";