Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 674
Jinu Joseph Daniel Avatar asked Dec 11 '25 12:12

Jinu Joseph Daniel


2 Answers

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;
},
like image 70
ddaa Avatar answered Dec 14 '25 00:12

ddaa


This is a case where IE before IE9 and all other browsers do it differently. To get the current style on an object including whatever is applied to the object from stylesheets, you could use something like this:

function getStyle(el, cssprop) {
    if (document.defaultView && document.defaultView.getComputedStyle)
        return document.defaultView.getComputedStyle(el, null)[cssprop];
    else //IE
        return el.currentStyle[cssprop];
}
like image 26
jfriend00 Avatar answered Dec 14 '25 00:12

jfriend00