style.backgroundColor is an empty string in JavaScript

Unless you have directly defined the backgroundColor on the element itself, you have to use getComputedStyle() or currentStyle to get the value of a style property.

A method that is compatible with multiple browsers would look like this:

function getStyle(el,styleProp)
{
    if (el.currentStyle)
        return el.currentStyle[styleProp];

    return document.defaultView.getComputedStyle(el,null)[styleProp];
}

You can see a working example on jsFiddle.

More information:

  • See this page for more information about getComputedStyle().
  • See this page for more information about currentStyle (IE).
  • See this page for more information about browser compatibility issues.

Leave a Comment