This is the table I tested my code on:
<table id="myTable">
<tr>
<td><input type="text" value="hello" /></td>
<td><input type="checkbox" name="foo" value="2" /></td>
<td><input type="button" value="hi" /></td>
</tr>
</table>
Here is the code that worked:
// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
if(element.attachEvent) {
element.attachEvent(eventToHandle, eventHandler);
} else if(element.addEventListener) {
element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false);
} else {
element[eventToHandle] = eventHandler;
}
}
attachEventHandler(window, "onload", function() {
var myTable = document.getElementById("myTable");
var myTableCells = myTable.getElementsByTagName("td");
for(var cellIndex = 0; cellIndex < myTableCells.length; cellIndex++) {
var currentTableCell = myTableCells[cellIndex];
var originalBackgroundColor = currentTableCell.style.backgroundColor;
for(var childIndex = 0; childIndex < currentTableCell.childNodes.length; childIndex++) {
var currentChildNode = currentTableCell.childNodes[childIndex];
attachEventHandler(currentChildNode, "onfocus", function(e) {
(e.srcElement || e.target).parentNode.style.backgroundColor = "red";
});
attachEventHandler(currentChildNode, "onblur", function(e) {
(e.srcElement || e.target).parentNode.style.backgroundColor = originalBackgroundColor;
});
}
}
});
There are probably things here you could clean up, but I whipped this together quickly. This works even if there are multiple things in each cell.
This would be much easier, it should go without saying, if you used a library to assist you in this work - jQuery and MochiKit are the two I favor, though there are others that would work just as well.
Between the time I started writing this answer and the time I posted it, someone posted code that shows how you would do something like this in jQuery - as you can see, much shorter! Although I love libraries, I know some people either can't or will not use a library - in those cases my code should do the job.