Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading non-inline CSS style info from Javascript

Tags:

javascript

css

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

like image 226
OneNerd Avatar asked Dec 17 '22 07:12

OneNerd


2 Answers

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;
like image 150
Matt Bridges Avatar answered Dec 19 '22 20:12

Matt Bridges


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.

like image 36
ajm Avatar answered Dec 19 '22 20:12

ajm