开发者

Get all <style> tags and concatenate the contents into one <style> tag

开发者 https://www.devze.com 2023-03-28 06:18 出处:网络
I know I can get the style tag 开发者_Python百科with $(\'style\') but how can I get all style tags from the document and merge them into a single style block ?<script>

I know I can get the style tag 开发者_Python百科with

$('style')

but how can I get all style tags from the document and merge them into a single style block ?


<script>
var styles;
$("style").each(function(a,b){
    styles = styles + "\n" + b.html();
    $(this).remove();
});

$("#style").html('<style>'+ styles +'</style>');

</script>
<div id="style>

</div>


Here is how you can do it in two lines:

// add a new style element before the first one with all the rules
$('style:first').before('<style type="text/css" id="new">'+$('style').text()+'</style>');

// remove all the style elements except the one added above
$("style:not('#new')").remove();

Here is a demo Updated

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号