3

I want to get only the computed styles of the elements on a page, without all the inherited styles

var allElements = document.querySelectorAll( '*' );
for (var i=0;i<allElements.length;i++){

    var element = allElements[i];

    var css = getComputedStyle(element);

}

this obviously gets a gigantic list of all the styles.

I need only the 'computed styles' that would show up in Chrome's inspector thing when the "show inherited" checkbox is disabled.

What's the JS for this?

EDIT:

I'm basically looking to save all the css I've modified in Chrome inspector. I'm laying out things on a page and I'm playing with fonts and elements placement (dragging jquery draggables around). I want to save the positions and CSS of everything. Maybe I went way too complex and there's a simple way to save all the modified styles in Chrome inspector?

  • I don't think this is possible via normal JS. What problem are you really trying to solve? You can get styles directly attached to the element (not via a stylesheet) or you can get the net/net overall style including all style sheet rules. – jfriend00 Oct 29 '13 at 02:16

1 Answers1

3

Try getting computed styles of an element and its parent element, then remove identical properties:

var elems = document.getElementsByTagName('*');
var data = '';
for(var n=0;n<elems.length;n++){
    if(elems[n].parentNode.tagName){
    data+=elems[n].tagName + ': ' + elems[n].className+'\n';
        var style = [];
    var prStyle = [];
    var result = [];
    var css = window.getComputedStyle(elems[n], null);
    var prCss = window.getComputedStyle(elems[n].parentNode, null);
    for(var i=0;i<css.length;i++){
        if(css.getPropertyValue(css[i])){
            style[i] = css[i]+':'+css.getPropertyValue(css[i]);
        }
    }
    for(var i=0;i<prCss.length;i++){
        if(prCss.getPropertyValue(prCss[i])){
            prStyle[i] = prCss[i]+':'+prCss.getPropertyValue(prCss[i]);
        }
    }
    for(var i=0;i<style.length;i++){
        if(style[i]!=prStyle[i]){
            result.push(style[i]);
        }
    }
    for(var i=0;i<result.length;i++) data+=i+':'+result[i]+'\n';
}
data+='-----------------------\n';
}
return data;
abdulla
  • 61
  • 4