Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get CSS class definition from chrome developer tools console

I would like to programatically retrieve a set of CSS class definitions from chrome developer tools. In effect similar to what is displayed in styles tab in the right hand side. The input needs to be a class name and the output should be all the styles defined in it.

I'm aware of getComputedStyle DOM method, but this doesn't separate into separate classes which I need.

like image 560
dparnas Avatar asked Dec 19 '22 03:12

dparnas


1 Answers

This approach worked for me (stackoverflow.com/a/27527462/1023562):

 /**
     * Gets styles by a classname
     * 
     * @notice The className must be 1:1 the same as in the CSS
     * @param string className_
     */
    function getStyle(className_) {
    var styleSheets = window.document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    for(var i = 0; i < styleSheetsLength; i++){
        var classes = styleSheets[i].rules || styleSheets[i].cssRules;
        var classesLength = classes.length;
        for (var x = 0; x < classesLength; x++) {
            if (classes[x].selectorText == className_) {
                var ret;
                if(classes[x].cssText){
                    ret = classes[x].cssText;
                } else {
                    ret = classes[x].style.cssText;
                }
                if(ret.indexOf(classes[x].selectorText) == -1){
                    ret = classes[x].selectorText + "{" + ret + "}";
                }
                return ret;
            }
        }
    }

}

It lets you invoke the javascript code in Chrome console like this:

console.log(getStyle('#heder_logo a')); 

and get results like this:

> #heder_logo a { width: 200px; height: 114px; display: block; }.

I did have issues with some CSS files which were not on the same domain (they were pulled from CDN), but there are variety of proposals in that thread, so some should work for you.

like image 103
Ivan Jovović Avatar answered Dec 24 '22 01:12

Ivan Jovović