Alex Rivera | Logout

getComputedStyle (or) $.css(map) <-- to get every style declaration

Asked 2010-04-01T06:01:37.120
11

Aside from looping through an array that has each style property declared, is there any way to get a key/value output of all styling of a dom element?

My fallback is iterating through the keys listed on: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle

Edit
Report

1 Answer

18

is there any way to get a key/value output of all styling of a dom element?

Yes, but don't expect the exact handling of values (units etc.) to be the same cross-browser.

var styles= [];

// The DOM Level 2 CSS way
//
if ('getComputedStyle' in window) {
    var cs= getComputedStyle(element, '');
    if (cs.length!==0)
        for (var i= 0; i<cs.length; i++)
            styles.push([cs.item(i), cs.getPropertyValue(cs.item(i))]);

    // Opera workaround. Opera doesn't support `item`/`length`
    // on CSSStyleDeclaration.
    //
    else
        for (var k in cs)
            if (cs.hasOwnProperty(k))
                styles.push([k, cs[k]]);

// The IE way
//
} else if ('currentStyle' in element) {
    var cs= element.currentStyle;
    for (var k in cs)
        styles.push([k, cs[k]]);
}
answered 2010-04-01T14:55:19.893

Your Answer