2

I am trying to append to a string in a for loop. I can alert each value bieng looped but i cant append for some reason:

<html>
    <head>
        <script type="text/javascript" language="javascript">
            function doIt(){
                    var styleSheet = document.styleSheets[0];
                    var css="";
                    for (i=0; i<=styleSheet.cssRules.length; i++)
                    {
                        css += styleSheet.cssRules[i].cssText;
                        //alert(styleSheet.cssRules[i].cssText); //WORKS
                    }
            }
        </script>
        <style type="text/css">
            .container{display:none;}
            .markup-container{color:#404040;}
            .title{text:decoration:underline;}
            .body{color:#000;}
        </style>
    </head>
    <body>
        <input type="button" id="button" onmousedown="doIt()">
        <div class="container">
            <div class="markup-container">
                <div class="title">This is a title with some markup</div>
                <div class="body">This is the body with some markup and it's longer ^^</div>
            </div>
        </div>
    </body>
</html>
2
  • When you say "can't append", what does that mean? The string is still empty? You might want to try calling toString() on the cssText, though you shouldn't have to. Commented Jun 21, 2010 at 0:40
  • I can do something like css += "somestring"; and that works. Commented Jun 21, 2010 at 0:45

1 Answer 1

2

Your for loop is off by one :)

for (i=0; i<=styleSheet.cssRules.length; i++)
//should be:
for (i=0; i<styleSheet.cssRules.length; i++)

When this happens at the end:

styleSheet.cssRules[styleSheet.cssRules.length].cssText

You'll get an error, because you're one past the length of the array, and styleSheet.cssRules[i] is undefined, resulting in an error when you try to access the .cssText property on it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.