I have to get what are all the CSS styles used in a 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;
}
Is it possible to do?
For inline stylesheets, you can get the content out of the normal DOM like with any other element:
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 thedocument.styleSheets[].cssRules[].cssTextproperty.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.)