I needed to get the background color of an element that was previously defined by a stylesheet in order to determine the style for the new element that will be created dynamically using javascript.
I tried using the 'backgroundColor' property but the return value was empty. The value needs to be set first with js then it can be retrieved with the property (not in hexadecimal). Is there other alternative to this without having to modify the element? Like using offsetWidth?
CSS:
#mybox {
width: 100px;
height: 100px;
margin: auto;
background-color: #eb5;
}
#buttons {
text-align: center;
}
HTML:
<div id="mybox"></div> <div id="buttons">
<input type="button" value="set" onclick="setColor('#ddd')" />
<input type="button" value="get" onclick="getColor()" />
</div>
JS:
function getColor(color){
var box = document.getElementById("mybox");
alert(box.style.backgroundColor);
}
function setColor(color){
var box = document.getElementById("mybox");
box.style.backgroundColor = color;
}
JSFiddle: http://jsfiddle.net/mevmike/FjkYA/