PDA

View Full Version : Dynamically colouring table cells



Tonyp543212003
11-17-2009, 04:19 PM
I have a table rendered from an external source in this format:

<table>
<tr class="ms-vb">
<td>October 2009</td>
<td>/\</td>
<td>/\</td>
<td>##</td>
<td>##</td>
<td>/\</td>
etc...
</tr>
</table>

I want to colour the cells depending on the content. e.g ## = red, /\ = green, etc... I canít make any changes to the rendered html so it has to be done dynamically using JavaScript.

Does anyone know how to do this? Any help would be greatly appreciated. I could do this easily if there was an id created dynamically but without that Iím not sure how to colour the cells individually.

Thanks,
Tony

Tonyp543212003
11-17-2009, 05:06 PM
<script type="text/javascript">
function changeContent()
{
var rowpos = 0;
var colpos = 0;
for (var rowpos = 0; rowpos <= 10; rowpos++)
{
var x=document.getElementByAttribute('summary,Marks Grid').rows[rowpos].cells;
for (var colpos = 0; colpos <= 10; colpos++)
{
var checkcell = x[colpos].innerHTML;
if (checkcell == "##"){
x[colpos].innerHTML="Away";
}
else{
x[colpos].innerHTML="Present";
}
}
}
}
</script>


<input type="button" onclick="changeContent()" value="Show changes">


<table rules="all" summary="Marks Grid" border="1">
<tr>
<td>##</td>
<td>##</td>
<td> </td>
<td>##</td>
<td> </td>
<td>##</td>
</tr>
<tr>
<td>##</td>
<td>##</td>
<td> </td>
<td>##</td>
<td> </td>
<td>##</td>
</tr>
</table>

vwphillips
11-17-2009, 05:27 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
</head>

<body>
<table>
<tr class="ms-vb">
<td>October 2009</td>
<td>/\</td>
<td>/\</td>
<td>##</td>
<td>##</td>
<td>/\</td>
etc...
</tr>
</table>
<script type="text/javascript">
/*<![CDATA[*/
var tables=document.body.getElementsByTagName('TABLE');
for (var rows,cells,z0=0;z0<tables.length;z0++){
rows=tables[z0].rows;
for (var z0a=0;z0a<rows.length;z0a++){
cells=rows[z0a].cells;
for (var txt,z0b=0;z0b<cells.length;z0b++){
txt=cells[z0b].innerHTML;
if (txt=='/\\'){
cells[z0b].style.backgroundColor='red';
}
else if (txt=='##'){
cells[z0b].style.backgroundColor='green';
}
}
}
}


/*]]>*/
</script>
</body>

</html>

Tonyp543212003
11-17-2009, 07:37 PM
Wow thats fantastic vic, you really know your stuff. I have been stuck on this problem on and off for months trying different approaches.

Thanks!!