views:

71

answers:

1

I have to get what are all the css styles used in html file using javascript.

 <html>
  <head>
       <style type="text/css">
         body{
        border:1px solid silver;
         }

  .mydiv{
     color:blue;
    }
   </style>

 </head>
 <body>
 </body>
</html>

if the above code is my html I have to write one javascript function inside the head which returns a string like this body{ border:1px solid silver; }

.mydiv{ color:blue; }

I tried googling..I could not find.Is it possible to do? Help me please!!!!!!!!

+2  A: 

For inline stylesheets, you can get the content out of the normal DOM like with any other element:

document.getElementsByTagName('style')[0].firstChild.data

For external, linked stylesheets it's more problematic. In modern browsers, you can get the text of every rule (including inline, linked and @imported stylesheets) from the document.styleSheets[].cssRules[].cssText property.

Unfortunately IE does not implement this DOM Level 2 Style/CSS standard, instead using its own subtly different version of the StyleSheet and CSSRule interfaces. So you need some sniff-and-branch code to recreate rules in IE, and the text might not be exactly the same as the original. (In particular, IE will ALL-CAPS your property names and lose whitespace.)

var css= [];

for (var sheeti= 0; sheeti<document.styleSheets.length; sheeti++) {
    var sheet= document.styleSheets[sheeti];
    var rules= ('cssRules' in sheet)? sheet.cssRules : sheet.rules;
    for (var rulei= 0; rulei<rules.length; rulei++) {
        var rule= rules[rulei];
        if ('cssText' in rule)
            css.push(rule.cssText);
        else
            css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n');
    }
}

return css.join('\n');
bobince
Did you really call the variable sheeti?? :) It's indeed a sheeti variable..
Faruz
Thanks bobince...Worked fine in all the browsers...
BlackPanther