...

View Full Version : Change styles of th and td elements in a table



guvenck
06-11-2007, 03:34 PM
Hello,

I have a table with id="testblock" like this:



<table id="testblock" cellspacing="0" cellpadding="0">
<tr>
<th>Block Title</th>
</tr>
<tr>
<td>Any text here</td>
</tr>
</table>


I am trying to change the styles with Javascript and have no problems with the table related styles. But I can't change the styles of th and td elements.




/* these do work */
testblock.style.borderWidth = TableBorderWidth;
testblock.style.borderSpacing = TableBorderSpacing;
testblock.style.borderStyle = TableBorderStyle;
testblock.style.borderColor = TableBorderColor;
testblock.style.backgroundColor = TableBackgroundColor;

/* these do not */
testblock.th.style.padding = ThTdPadding;
testblock.th.style.backgroundColor = ThBackgroundColor;
testblock.th.style.color = ThColor;
testblock.td.style.padding = ThTdPadding;


How can I change the styles of th and td elements?

glenngv
06-11-2007, 05:50 PM
var tbl = document.getElementById("testblock");
tbl.style.borderWidth = TableBorderWidth;
tbl.style.borderSpacing = TableBorderSpacing;
tbl.style.borderStyle = TableBorderStyle;
tbl.style.borderColor = TableBorderColor;
tbl.style.backgroundColor = TableBackgroundColor;

//th
var tHeaders = tbl.getElementsByTagName('th');
for (var i=0; i<tHeaders.length; i++){
tHeaders[i].style.padding = ThTdPadding;
tHeaders[i].style.backgroundColor = ThBackgroundColor;
tHeaders[i].style.color = ThColor;
}

//td
var tData = tbl.getElementsByTagName('td');
for (var i=0; i<tData.length; i++){
tData[i].style.padding = ThTdPadding;
}

guvenck
06-12-2007, 02:43 AM
Hi Glenn,

thanks for your help. You suggested a nice solution by using getElementsByTagName. I managed to overcome the problem by assigning seperate id's to th and td within the same table:



<table id="testblock" cellspacing="0" cellpadding="0">
<tr>
<th id="testblock_th">Block Title</th>
</tr>
<tr>
<td id="testblock_td">Any text here</td>
</tr>
</table>


and



var testblock = document.getElementById("testblock");
testblock.style.borderWidth = TableBorderWidth;
testblock.style.borderSpacing = TableBorderSpacing;
testblock.style.borderStyle = TableBorderStyle;
testblock.style.borderColor = TableBorderColor;
testblock.style.backgroundColor = TableBackgroundColor;

var testblock_th = document.getElementById("testblock_th");
testblock_th.style.padding = ThTdPadding;
testblock_th.style.backgroundColor = ThBackgroundColor;
testblock_th.style.color = ThColor;

var testblock_td = document.getElementById("testblock_td");
testblock_td.style.padding = ThTdPadding;



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum