Categories:

Getting global and external style sheet values in Firefox

In Firefox (and other browsers such as Opera, Safari, and Google Chrome), getting the CSS property values of global/external style sheets is done using a different method, "document.defaultView.getComputedStyle". Like IE's "currentStyle" object, it returns an object that contains the cascaded values of all CSS properties applied to an element. To get the value to a specific cascaded CSS property, you'd just look up that property within the returned object. Lets jump straight to an example, which is probably the quickest way to illustrate how "document.defaultView.getComputedStyle" works:

<head>
<style type="text/css">
#test{
width: 100px;
height: 80px;
background-color: yellow;
}
</style>
</head>

<body>
<div id="test">This is some text</div>

<script type="text/javascript">
var mydiv=document.getElementById("test")
var inheritedstyle=document.defaultView.getComputedStyle(mydiv, "")
var divwidth=inheritedstyle.width //contains "100px"
var divbgcolor=inheritedstyle.backgroundColor //contains "yellow"
</script>
</body>

As you can see, "document.defaultView.getComputedStyle" operates in the exact same manner as IE's "currentStyle" object, though you access this method from the document, instead of as a property of a DOM element. getComputedStyle() accepts two parameters- a reference to the desired element, plus a string specifying the pseudo-element to match. For regular elements, you should enter a blank string ("") for the later. Upon invoking this method, the CSS property to retrieve the cascaded value of should also be accessed using the camelCase convention (ie: "inheritedstyle.backgroundColor").

Before moving on, it's worth mentioning that Firefox supports another object, window.getComputedStyle, which behaves similarly to "document.defaultView.getComputedStyle". However, that object isn't recognized by some browsers such as Safari, so it should be avoided.

Ok, now that we have the techniques for getting the cascaded CSS property values across browsers down, lets see how to merge the two into a single, cross browser one.

Cross browser function for retrieving global/external CSS properties