Try this.
I loop through all style elements in dom, storing the rules and removing them from the dom when stored.
Then build the less style sheet, including the discovered style rules.
Finally, retrieve the less script and parse the style rules, adding them to the body, then set the master class to the body.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
//Loop through all style elements in dom, storing the rules and removing them from the dom when stored
var styles = "";
$.each($("style"), function(index, value){
styles += $(value).text();
$(value).remove();
});
//Build the less stylesheet, including the discovered style rules
var lessStyles = ".master { " + styles + " }";
//Retrieve less and parse the style rules, adding them to the body, then set the master class to the body
$.getScript("http://cdnjs.cloudflare.com/ajax/libs/less.js/1.7.0/less.min.js",function(){
var parser = new(less.Parser);
parser.parse(lessStyles, function (err, tree) {
if (err) { return console.error(err) }
var css = tree.toCSS();
$("<style/>").html(css).appendTo("body");
$("body").addClass("master");
});
});
});
</script>
<style type="text/css">
h2{
color:green;
}
</style>
</head>
<body>
<style type="text/css">
.class2{
color:red;
}
</style>
<h1 class="class2">H1</h1>
<h2>H2</h1>
</body>
</html>