There are two parts to this:
Getting the element
Getting the color assigned to it
Getting the element
If you know the cell ID, you can use document.getElementById:
var element = document.getElementById("the-id");
If you want to do this in response to an event that happens on the cell, for instance a click, you can use an event handler. For instance, suppose the table has the id "my-table":
document.getElementById("my-table").addEventListener("click", function(event) {
var element = event.target;
while (element && element.tagName !== "TD") {
if (element === this) {
// No cell was clicked
return;
}
element = element.parentNode;
}
// ...use element here
});
That hooks the click event on the table (so you don't have to hook it on every single cell), then when the click reaches the table, finds the td that the click passed through on its way to the table (if any).
Note: Old versions IE (IE8 and earlier) don't have addEventListener, they have Microsoft's predecessor to it, attachEvent. This answer shows how to work around that if you need to.
Getting the color
If you assigned the color directly on the element, via the style attribute (<td style="color: ..."...), you can use the style object on the element:
var color = element.style.color;
If it's assigned via a stylesheet, that won't work, you need to use getComputedStyle instead:
var color = getComputedStyle(element).color;
Again, old versions of IE are a pain in this regard, they don't have getComputedStyle but they do have a currentStyle property on elements, so you can polyfill (shim) getComputedStyle:
if (!window.getComputedStyle) {
window.getComputedStyle = function(element, pseudo) {
if (typeof pseudo !== "undefined") {
throw "The second argument of getComputedStyle can't be polyfilled";
}
return element.currentStyle;
};
}
Example
Here's an example (modern browsers only) where you click a cell to get its color:
// Hook click on the table
document.getElementById("my-table").addEventListener("click", function(event) {
var element = event.target;
while (element && element.tagName !== "TD") {
if (element === this) {
// No cell was clicked
return;
}
element = element.parentNode;
}
// Show the color
alert("Color: " + getComputedStyle(element).color);
}, false);
.foo {
color: red;
}
.bar {
color: green;
}
.biz {
color: blue;
}
.baz {
color: #880;
}
<table id="my-table">
<tbody>
<tr>
<td class="foo">foo</td>
<td class="bar">bar</td>
</tr>
<tr>
<td class="biz">biz</td>
<td class="baz">baz</td>
</tr>
</tbody>
</table>