Search code examples
javascriptcssstylesstylesheet

Accessing CSS class using javascript


How can i access the style declaration of an element specified using external or embedded stylesheet.For ex: how to access the width property of an element which is defined in an embeded stylesheet using the id selector.. I know CSSRules object can do this...But it is browser dependent.For ex:in chrome ,the object is null...So what is the browser independent way to do this?


Solution

  • This is really browser dependent... I have a bit of code which I use to make an auto-expand text area, adapted from code found there.

    Note, the $ function here is from Prototype.

    function getStyleFromCss(el, style) {
        /* Hack required by IE */
        var value = $(el).getStyle(style);
        if (!value) {
            /* For other browsers. Actually this equals 'window'. Use that
             *  if Opera fails on you. */
            if(document.defaultView) {
                value = document.defaultView.getComputedStyle(el, null).
                    getPropertyValue(style);
                // for IE
            } else if(el.currentStyle) {
                value = el.currentStyle[style];
            }
        }
        if(value.length > 0){
            /* if the value returned has the word px in it, we check for
             *  the letter x */
            if (value.charAt(value.length-1) == "x") {
                value = parseInt(value.substring(0, value.length-2));
            }
        }
        return value;
    }
    

    The getStyle() function from Prototype is defined this way, you should be able to easily adapt it to your needs.

    getStyle: function(element, style) {
      element = $(element);
      style = style == 'float' ? 'cssFloat' : style.camelize();
      var value = element.style[style];
      if (!value || value == 'auto') {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css[style] : null;
      }
      if (style == 'opacity') return value ? parseFloat(value) : 1.0;
      return value == 'auto' ? null : value;
    },