0

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')" />
    &nbsp;
    <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/

Michael Erwin
  • 47
  • 1
  • 6

1 Answers1

1

Try this:

function getStyle(element, property) {
    if (element.currentStyle)
        return this.currentStyle[property];
    else if (getComputedStyle)
        return getComputedStyle(element, null)[property];
    else
        return element.style[property];
}

Put this code at the beginning of your script file, and access it this way

function getColor(color){
    var box = document.getElementById("mybox");
    alert(getStyle(box, 'backgroundColor'));
}

EDIT: "compressed" version

function getStyle(element, property) {
    return getComputedStyle ? getComputedStyle(element, null)[property] : 
    element.currentStyle ? element.currentStyle[property] : element.style[property];
}
Niccolò Campolungo
  • 10,812
  • 3
  • 29
  • 37
  • This piece of code is reminiscent of prototype.js... why is it a bad idea? maybe defaultView is not supported until IE9.. https://developer.mozilla.org/en-US/docs/Web/API/document.defaultView – Herrington Darkholme Jun 16 '13 at 17:54
  • 1
    @HerringtonDarkholme: Where's Prototype today? Okay, that's a bit sarky. :-) (And note: I used to be involved with the Prototype project, back in 2005-2006.) But again, if it won't work on important browsers (IE8 has ~23% of world users), it's not a good idea. – T.J. Crowder Jun 16 '13 at 17:54
  • That one works. My target browser was those that only support HTML5. – Michael Erwin Jun 16 '13 at 17:57
  • Even better, I think that you can safely extend the DOM. Right @T.J.Crowder ? – Niccolò Campolungo Jun 16 '13 at 17:59