Monday, March 2, 2009

How to Get the CURRENT Style of an Element in Firefox

I was trying to write some Javascript to get some style information about an HTML element. My instinct was to get the element object and access its 'style' property. But this only seemed to work some of the time, which was particularly frustrating! Eventually, I figured it out...

What I tried originally was something like the following:
elem = document.getElementById('myId');
height = elem.style.height;
bg     = elem.style.backgroundColor;
But that doesn't work if the style has not been set for that item explicitly in a stylesheet or in the HTML style tag. This means that if the style for the element was inherited from parent elements or the defaults were used, then the style will not be reflected in the element's style element.

So, how does one find the current style of an element when it has not been explicitly set? I was surprised at how hard it was to find the answer to this seemingly simple need...

Also to my surprise was that it was extremely easy to do in Internet Explorer. Most of the other things I try to do in IE are much harder, but in this case, all you have to do is access the currentStyle property. This is the style of the element as calculated and displayed by the browser, as opposed to the style that was specified  in CSS (which in this case was empty).

In Firefox, it wasn't quite as straight-forward. Instead of using a dynamic property set by the browser, you need to use a function. Firefox provides the window.getComputedStyle() function for getting the as-displayed style of an element.

For example,
elem = document.getElementById('myId');
if (window.getComputedStyle) {
   height = window.getComputedStyle( elem, null ).height;
   bg     = window.getComputedStyle( elem, null ).backgroundColor;
}
else {
   height = elem.currentStyle.height;
   bg     = elem.currentStyle.backgroundColor;
}

A little more tersely, one could get a reference to the style object using a conditional expression based on the existence of the getComputedStyle function:
elem = document.getElementById('myId');
style = (window.getComputedStyle
         ? window.getComputedStyle( elem, null ) : elem.currentStyle);
height = style.height;
bg     = style.backgroundColor;

That type of shorthand technique is nice if you have a lot of things to do with that style object, since you don't have to keep typing 'elem.currentStyle' or 'window.getComputedStyle'.

No comments: