You must really use a different approach to achieve this.
If you really want to go with what you have, you will have to replace many things in the meaning of textarea. To give you an idea, in the snippet below, I replace the html and body style declarations with id ( #readout ) to apply styles to the #readout div , not the body on the page. It works for the body , but what about all the other possible declarations?
I am sure that I am a true noob when it comes to regex, and I am sure that this can be done much better, but all this is not necessary.
$("#tryit").keyup(function() { var style = $(this).val().match(/<style>(.*)<\/style>/); if (style !== null && style.length > 0) { var bodyReplace = style[1].replace(/(^|\s)(html)|(body)(\s|$)/ig, '#readout'); } var input = $(this).val(); $("#readout").html(input.replace(/<style>.*<\/style>/, '<style>'+bodyReplace+'</style>')); }); $("#tryit").keyup();
#readout { height: 400px; width: 48%; border: 1px solid black; overflow: auto; float: right; clear: none; display: inline-block; } #tryit { height: 396px; width: 50%; float: left; clear: none; display: inline-block; font-family: monospace; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea name="tryit" id="tryit" rows="10"><!doctype html> <html> <head> <title>New Webpage</title><style>body {background: black; color: red }</style> </head> <body><h1>Hello</h1> </body> </html> </textarea> <div id="readout"></div>
Another problem is that the <doctype> , <html> , <head> and <body> elements in your textarea do not really exist. Take a look at the source and you will find out that they are not there, and they do not belong there. In doing so, I would say with the solution mentioned in the comment of Barmar, who suggested using iframe .
This is actually not so difficult. One quick and dirty way is to split the blob into textarea value and add this attribute to the original iframe attribute. This will even make it easier to separate your HTML and CSS with another CSS text field and enter its value as a stylesheet at the beginning of the iframe . Since I cannot use the iframe object in sn snipet tool due to security in the sandbox, check this
JSFIDDLE
and I'm sure you get this idea.
source share