DOM methods like document.getElementById()
create objects which point to- and contains certain details about- a specified HTMLElement or set of elements.
Unfortunately the .style
property only knows about the style properties set using that same feature. In the example below, clicking what color?
will not work until you have clicked change color
.
<html>
<head>
<script>
function whatColor() {
var d = document.getElementById( 'ddd' );
alert( d.style.backgroundColor );
}
function changeColor() {
var d = document.getElementById( 'ddd' );
d.style.backgroundColor='orange';
}
</script>
<style>
#ddd {
background-color:gray;
}
</style>
</head>
<body>
<input type="button" onclick="whatColor();" value="what color?" />
<input type="button" onclick="changeColor();" value="change color" />
<div id="ddd"> </div>
</body>
</html>
I recommend reading PKK's great page on getComputedStyle and currentStyle (IE, of course is different) http://www.quirksmode.org/dom/getstyles.html
At the end of the tutorial, there is a very decent function for your purposes, although frameworks such as jQuery do provide very convenient & powerful functions for styling page elements: http://api.jquery.com/css/