JavaScript

Get computed style

Sometimes you want to get the width of an element, and the obvious way of getting it does not work.

element.style.width; // (empty string)

Yeah, I know it should be this easy but it is not. Instead we have to get the computed style. The only time we can check the style property and get a value is if we set it our self.

element.style.width = "200px";
... later in the code ...
element.style.width; // 200px

But, to get the dynamic value we have to check the computed style. Let's try.

document.defaultView.getComputedStyle(element, null)["width"]; // 480px; 

Yeah, very hard to memorize. The computed style method takes two arguments, the first one is the element to get the property from and the second one is a pseudo-elements. It returns a CSSStyleDeclaration object. The object has all the CSS properties.

The only problem is that IE has it's own way of implementing it. So we have to write a function that use the method supported by the browser.

var computedStyle = function (el,style) {
    var cs;
    if (typeof el.currentStyle != 'undefined'){
        cs = el.currentStyle;
    }
    else {
        cs = document.defaultView.getComputedStyle(el,null);
    }
    return cs[style];
};

Now we can get the width of the element using this function:

computedStyle(element,"width"); // 480px

Note, you can get other properties too like the height, display, overflow, and so on.


Comments

Let's hear your thoughts

For my eyes only

There are no comments added yet.