Forum Moderators: open

Message Too Old, No Replies

Getting body bg color with js

         

asantos

1:03 am on Jun 29, 2006 (gmt 0)

10+ Year Member



Suposse i have

<html><head></head><body>blabla</body></html>

The CSS tells me that the body has a #FFF background-color.

How can I get the body bg color with js?
I tried
alert(document.body.style.backgroundColor);
nothing happens.

Any ideas?

texmex

4:13 am on Jun 29, 2006 (gmt 0)

10+ Year Member



The method you are attempting will only work if the style is directly applied to the tag itself. such as:

<body style="background-color:green">

Any style that is applied by a separate style definition is NOT inserted into the style property of the element.

Although it may look like it, the browser will compute the style to be applied by looking at any applied style definitions in the document that apply for the tag in question.

Unfortunately there is no easy answer to this one. Especially when you take into account the various browsers available.

This would come close.


var bdy=document.getElementsByTagName("BODY")[0];

if (bdy.currentStyle)
var y = bdy.currentStyle["backgroundColor"];
else if (window.getComputedStyle)
var y = Window.getComputedStyle(bdy,"")["backgroundColor"];
alert(y);

Something else you'll have to bear in mind is that some browsers will return the colour in Hex notation (such as "#00FF00" for green),
Whereas others will return RGB notation (such as "rgb(0,128,0)" for green). Or you may even get a word (such as "green")

asantos

5:01 am on Jun 29, 2006 (gmt 0)

10+ Year Member



texmes, i really appreciate your answer. As i can see there are a lot of alternatives... but the results wont always be the same. Ill implement that solution tomorrow at the office and then ill let you know. Thanks again.

adni18

4:28 pm on Jun 30, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Actually, I seem to remember reading a few years back about a currentStyle property of <BODY>. I can't test it now, but try accessing document.body.currentStyle.backgroundColor and see what it gives you. :)

edit: sorry texmex! I didn't see your post! :P