6

Could anyone tell me why document.body.style.backgroundColor doesn't work with external CSS style sheet? I mean: when I have

body
{
    background-color: red;   
}

in my css style sheet javascript alert alert(document.body.style.backgroundColor); shows empty string. Working example here.

but when I have

<body style="background-color: red;"></body>

it shows (as it should) "red". Example here.

I would appreciate a good explanation and even more an answer how to fix the first example.

KaroCodes
  • 246
  • 2
  • 13

3 Answers3

7

.style property on a DOM element returns a CSSStyleDeclaration for that particular element. By definition of a .style access, it is the styles of the element itself. style= attribute controls the same value, thus you see the result.

However, CSS applied using a selector are not directly a property of an element. Consider the CSS p { color: red }. This CSS applies to multiple elements, and as such, make no sense being overrideable on a level of a particular element.

What you are looking for is window.getComputedStyle to get a read-only view on the element's current styles: window.getComputedStyle(document.body).backgroundColor indeed returns a correct value, as seen in the updated Fiddle.

Denis
  • 5,061
  • 1
  • 20
  • 22
1

you are using jquery buddy

try this it will give rgb value

alert($('body').css('background-color'));

Js Fiddle

if you want hex value try this

Js Fiddle

Vitorino fernandes
  • 15,794
  • 3
  • 20
  • 39
  • And when you change the library in jsfiddle to "none" you get the result you expect – Dave Bush Sep 27 '14 at 12:19
  • "you are using jquery" — The question doesn't mention jQuery, the `jquery` tag is not used, the `javascript` tag says *Unless a tag for a framework or library is also included, a pure JavaScript answer is expected* – Quentin Sep 27 '14 at 12:22
  • but in his js fiddle she has linked jquery – Vitorino fernandes Sep 27 '14 at 12:23
1

Try this

var element =     document.getElementsByTagName('body')[0];                     
var style = window.getComputedStyle(element),
var bgColor    = style.getPropertyValue('background-color');
Danis
  • 1,978
  • 3
  • 16
  • 27