...

View Full Version : detecting tds of a certain table



LuckBox
06-26-2009, 02:56 PM
Hello,

I would to change the color of some td cells if there is text in it.
Right now this code does the job, but it changes the color of evry table.
I'd like to know a way to do this on one table in my page and not all of them.



var count='0';
var TDs=document.getElementsByTagName('td')
var length=TDs.length;
i='0';
while(i<length){
if (TDs[i].innerHTML != '') {
TDs[i].style.backgroundColor = "white";
count++;
}
i++;
}

itsallkizza
06-26-2009, 03:14 PM
Here ya go:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Test</title>
<script type="text/javascript">
// <![CDATA[

function changeEmptyTDBG(table,color)
{
var tds = table.getElementsByTagName("td");
for (var i=0;i<tds.length;i++)
{
if (!tds[i].innerHTML) tds[i].style.backgroundColor = color;
}
}

window.onload = function()
{
changeEmptyTDBG(document.getElementById("table1"),"red");
}

// ]]>
</script>
</head>
<body>

<table id="table1">
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
</tr>
<tr>
<td>stuff</td>
<td></td>
<td>stuff</td>
<td></td>
</tr>
<tr>
<td>more stuff</td>
<td>more stuff</td>
<td></td>
<td>more stuff</td>
</tr>
</table>

<br />

<table id="table2">
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
</tr>
<tr>
<td>stuff</td>
<td>stuff</td>
<td>stuff</td>
<td>stuff</td>
</tr>
<tr>
<td>more stuff</td>
<td>more stuff</td>
<td>more stuff</td>
<td>more stuff</td>
</tr>
</table>

</body>
</html>


Essentially you just need a reference to the table in question (in the above case I used its id attribute) and replace "document" with that reference.

Kor
06-26-2009, 03:36 PM
I would have rather used a RegExp test, in case the cells are structured like:


<td>
</td>
...or ...
<td> </td>

so that the following will cover all the possibilities:


if (!/\S+/.test(tds[i].innerHTML)) tds[i].style.backgroundColor = color;

LuckBox
06-26-2009, 03:51 PM
thank you, it works now!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum