4

I know I must be missing something here, but I cannot seem to get this to work.

I have assigned a background color to the body of an html document using the style tags inside the head section of the document, but when I try to read it via JavaScript, I get nothing:

<html>
<head>
<style>
body { background-color: #ff0; }
</style>
</head>
<body>
<a href="#" onclick='alert(document.body.style.backgroundColor)'>Click Here</a>
</body>
</html>

.. however, if I assign the style inline, it works:

<html>
<head></head>
<body style='background-color: #ff0;'>
<a href="#" onclick='alert(document.body.style.backgroundColor)'>Click Here</a>
</body>
</html>

I know I am missing something basic, but my mind is not in the zone today -- can anyone tell me why my first scenario is not working?

Thanks

asked Jul 8, 2009 at 14:12
2

4 Answers 4

7

The style property of a DOM element refers only to the element's inline styles.

Depending on the browser, you can get the actual style of an element using DOM CSS

In firefox, for example:

var body = document.getElementsByTagName("body")[0];
var bg = window.getComputedStyle(body, null).backgroundColor;

Or in IE:

var body = document.getElementsByTagName("body")[0];
var bg = body.currentStyle.backgroundColor;
answered Jul 8, 2009 at 14:23
Sign up to request clarification or add additional context in comments.

Comments

4

In this case, you'll want the computedStyle on the Element as the style attribute hasn't been set yet. In IE, you'll need to check the Element's currentStyle property, via something like this.

answered Jul 8, 2009 at 14:21

Comments

1

Here is a function you can use (without the use of a framework ie) that was posted here by InsDel:

function getStyle(className) {
 var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
 for(var x=0;x<classes.length;x++) {
 if(classes[x].selectorText==className) {
 (classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
 }
 }
}
getStyle('.test')
answered Jul 8, 2009 at 14:20

Comments

0

That's just how css works. There's no straight-forward way to get the computed css attributes of an element within Javascript, that I know of, short of browser specific utilities.

answered Jul 8, 2009 at 14:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.