Saturday, February 26, 2011

How to get element's style property when it's not set.

Sometimes when You want to get some element's style property directly using the way, You may get quite not what You were expecting.
This code below is my proposition of a function that gets calculated style value of an element.
function elementCurrentStyle(element, styleName){
    if (element.currentStyle){
        var i = 0, temp = "", changeCase = false;
        for (i = 0; i < styleName.length; i++)
            if (styleName[i] != '-'){
                temp += (changeCase ? styleName[i].toUpperCase() : styleName[i]);
                changeCase = false;
            } else {
                changeCase = true;
        styleName = temp;
        return element.currentStyle[styleName];
    } else {
        return getComputedStyle(element, null).getPropertyValue(styleName);
However, there is something You should know while calling this function. Let's imagine that there is a DIV element somewhere in our HTML document. Now, we're going to set it's border style like that:
var d1 = document.getElementById("div1"); = "1px solid red";
All right, now calling
elementCurrentStyle(d1, "border"); 
should return "1px solid red" string, but it returns an empty string. Instead of calling the above, use something like that:
elementCurrentStyle(d1, "border-top-width"); 
This will return "1px" and
elementCurrentStyle(d1, "border-top-color"); 
will return "rgb(255, 0, 0)".

One more thing to remember is that the parameter styleName should always be a CSS style name, not the DOM name. ("border-top-width" not the "borderTopWidth").

This code was tested under IE, FF and Chrome. If You find out that it's not working under Your browser, or have a better proposition, please, let me know.

No comments:

Post a Comment