I want to have an alert pop up that shows me the background of a table cell whenever i click on it. I just can't seem to find or figure out how to grab the background color.
My table cell looks like this:
<td id="s0" onclick="selectCell(event)">0</td>
My selectCell function looks like this:
function selectCell(e){
alert(e.target.backgroundColor); //this gives me 'undefined'
alert(e.target.bgcolor); //this gives me 'undefined'
alert(e.target.bgColor); //nothing shows up. i don't believe this is a valid property
//once i know i am properly grabbing the color i will do stuff with it here.
}
My CSS looks like this:
#s0 {
border: 1px solid;
background-color: yellow;
}
Any help would be greatly appreciated!!
The styles of a node are in the styles property, for example:
e.target.style.backgroundColor;
However this works only for those styles declared with the in-line style
attribute. If CSS is assigned (as it should be) using a stylesheet, you'll need to use:
window.getComputedStyle(e.target, null).backgroundColor;
Internet Explorer, unfortunately, doesn't implement the getComputedStyle()
option, instead offering currentStyle
(mind, they don't support e.target
either, I think, at least in versions prior to 8?). I don't have Internet Explorer with which to test, but the docs suggest that it should be used:
var e = window.event ? window.event : e,
elementNode = e.target !== null ? e.target : e.srcElement;
elementNode.currentStyle.backgroundColor;
References:
currentStyle
.Element.style
.window.getComputedStyle()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With