My problem is as it follows:
I have a piece of JavaScript code which generates a "new" document using document.write
and at first I write the entire heading of the web page. In that head I have a bit of CSS code which looks like this:
<style type='text/css'>
.black {background-color: black;}
.white {background-color: #ffffff;}
td {width:50px; height:50px;}
</style>
And JavaScript draws a table in the body section. Writing code is basically two for
loops which draw a chess board. But that doesn't even matter. Every td
element gets a class black
or white
by which it gets properly coloured. And every td
gets a onclick='changeBg(this)'
attribute.
Here is where the problem comes to life. I can not access the background color of the element that gets clicked. Function looks like so:
function changeBg(element)
{
alert(element.style.backgroundColor);
element.style.backgroundColor = "red";
}
At first I alert the color of the current element. It always alerts a blank notification. After I change the color to red and click on the element again it alerts red
. The td
's are coloured in the browser and if I inspect them with firebug the have background-color: black | white
;
What am I missing and how to fix this? I have realised that if I set td
color when creating them using style="color: black | white"
; it works but then I don't know to which class they belong.
You can get the currently applied style using window.getComputedStyle
- Docs
function changeBg(element) {
alert(window.getComputedStyle(element).backgroundColor);
element.style.backgroundColor = "red";
}
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