3

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;

    }
kag359six
  • 1,693
  • 2
  • 16
  • 21
  • How are you searching for the rule? I just did a Fiddle and your code seems to work! http://jsfiddle.net/kA24S/2/ – Thanizer Jun 28 '13 at 19:55
  • Really? I'm using it in Chrome and typed getRule(".dropmenu") and it doesn't work. Maybe it's just chrome? – kag359six Jun 28 '13 at 23:50
  • I am also using Chrome. Can I see the CSS you're using? – Thanizer Jun 28 '13 at 23:52
  • the name was changed to "menuopen" recently just to let you know it's not a mistake. – kag359six Jun 29 '13 at 00:25
  • The reason why I'm struggling is because I can't seem to reproduce your problem; your code seems to work perfectly fine. Take a look at this new jsFiddle I made. Review the code and tell me if this is what you're looking for: http://jsfiddle.net/GRFrr/1/ – Thanizer Jun 29 '13 at 01:39
  • 1
    [This](http://stackoverflow.com/questions/16965515/how-to-get-a-style-attribute-from-a-css-class-by-javascript-jquery/16966533#16966533) might be helpful – rlemon Jun 29 '13 at 03:10

1 Answers1

1

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).

Varun N
  • 51
  • 2