1

I'm wondering if anyone has had experience trying to output the css markup of a given element using javascript.

Note: Using Webkit only.

For example:

HTML:

<div id="css"></div>

Styling:

#css {
    background: #F1F3F5;
    border: 1px solid #B4BFC9;

    -moz-box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
}

nifty jQuery plugin? :)

alert($('#css').getCSS());

Alert

#css {
    background: #F1F3F5;
    border: 1px solid #B4BFC9;

    -moz-box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 1px rgba(0, 0, 0, 0.3);
}
Ryan
  • 21,437
  • 7
  • 25
  • 28
  • possible duplicate of [How do you read CSS rule values with JavaScript?](http://stackoverflow.com/questions/324486/how-do-you-read-css-rule-values-with-javascript) – Felix Kling Jul 08 '11 at 17:45
  • I have never thought of it but it would be cool. Not sure why you'd want it when Safari, Chrome, and Firefox all have inspector tools that would give you have information and more. – brenjt Jul 08 '11 at 17:46
  • 3
    There's no way to get both the `-moz-` values and the `-webkit-` values as unsupported rules are ignored – qwertymk Jul 08 '11 at 17:50

1 Answers1

2
function css(a){
    var sheets = document.styleSheets, o = {};
    for(var i in sheets) {
        var rules = sheets[i].rules || sheets[i].cssRules;
        for(var r in rules) {
            if(a.is(rules[r].selectorText)) {
                o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
            }
        }
    }
    return o;
}

function css2json(css){
        var s = {};
        if(!css) return s;
        if(css instanceof CSSStyleDeclaration) {
            for(var i in css) {
                if((css[i]).toLowerCase) {
                    s[(css[i]).toLowerCase()] = (css[css[i]]);
                }
            }
        } else if(typeof css == "string") {
            css = css.split("; ");          
            for (var i in css) {
                var l = css[i].split(": ");
                s[l[0].toLowerCase()] = (l[1]);
            };
        }
        return s;
    }

Usage:

var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • Works great. Thanks AlienWebguy :) – Ryan Jul 08 '11 at 18:21
  • However, this only works individually for each browser as they get filtered for unrecognized properties – as aforementioned by @qwertymk. – Ryan Jul 08 '11 at 18:35
  • 1
    can u get it to work if the element also has pseudo classes such as `::afetr`, `::before` and `:over` and show them as well? that would be the best! – vsync Mar 31 '12 at 20:09