Solution 1 :

No need to find head tag. Just read value from textarea and append that value on head like below.

var css = $("#txtStyle").val();
$('head').append('<style type="text/css">body {' + css + '}</style>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id='txtStyle' rows="4" cols="50">
background-color: red;
</textarea>

Problem :

I have a textarea in my page with a default HTML value in it. I want to get its value and append a style tag to the head tag of it. How can I do this?
I tried this but had no success:

var html = $( 'textarea' ).val();
$( html ).find( 'head' ).append( '<style></style>' );

Comments

Comment posted by Anis R.

Wait, an HTML document should only have one

Comment posted by Ehsan Mousavi

I mean head tag of html value in textarea.

Comment posted by Libra

@EhsanMousavi A textarea can have any text in it, what you are saying is not clear at all. Why would your textarea have a head tag? or any tag at all?

Comment posted by Ehsan Mousavi

Haven’t you seen sites like codepen or jsfiddle @Laif?

Comment posted by Libra

@EhsanMousavi What specifically about them? Like, you’re typing in raw HTML code into a text box and not rendering it?

Comment posted by Ehsan Mousavi

Thanks but not my answer.

By