Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this function returning a css rule?

I'm trying to write some helper functions so I can edit a css class through javascript. Here is what I have, but I don't understand why it keeps returning "undefined". Im using chrome for testing.

    function getRule(name, doDelete) { //takes a rule name and boolean

    if(document.styleSheets) { //check if there are stylesheets

        for(var i = 0; i < document.styleSheets.length; i++) { //loop through style sheets

            var currentSheet = document.styleSheets[i];
            if(currentSheet.cssRules) { //if the sheet has rules

                for(var h = 0; h < currentSheet.cssRules.length; h++) { //loop through css rules

                    var currentRule = currentSheet.cssRules[h];
                    if(currentRule.selectorText == name) { //if rule name is equal to the name given

                        return currentRule; //return the css rule

                    }

                }

            }

        }

    }

}

css being used:

    .menuopen {

    margin-left: auto;
    margin-right: auto;
    text-align: center;
    font-size: 20px;
    width: 960px;
    height: 200px;
    background-color: 3b7ea8;
    box-shadow: inset 0px 2px 5px 3px rgba(0,0,0,0.75);
    -webkit-animation-name: dropAnimation;
    -webkit-animation-duration: 2s;

    }
like image 435
kag359six Avatar asked Aug 23 '26 01:08

kag359six


1 Answers

Could one of these issues be the problem?
document.styleSheets[n].cssRules null when page accessed locally
cssRules is null for CSSStyleSheets from other domains
Regression: cssRules null when stylesheets loaded from local disk
These issues occur based on how your stylesheets are included and how you load your page (from disk or from a server).

like image 181
Varun N Avatar answered Aug 25 '26 16:08

Varun N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!