VagrantC
VagrantC

Reputation: 827

Issues rendering CSS and HTML from a textarea into a div element

I'm able to render HTML code typed up in a textarea into a div element next to it, but I'm having some issues with the CSS that it tries to render. The setup I have is similar to what w3schools has with their "try it" sections where there's a box on the left for writing code and a div on the right for the rendered html, but when I apply CSS to "body", it applies it instead to the entire web page instead of the div.

So if this code is typed into the textarea:

body {
    background: linear-gradient(45deg, red, blue, green);
}

It would change the background of the whole website instead of the background of the div that the webpage is rendered into. Is there any way to fix this or will this always be an issue? This is my function for rendering the textarea code:

$(document).ready(function(){
            $("#showmeImg").click(function(){
                $("#outputContainer").html($(editor.getValue()));
            });
        });

Clicking the 'showmeImg' will render the code from 'editor' into the 'outputContainer' div.

Upvotes: 0

Views: 394

Answers (2)

brianpck
brianpck

Reputation: 8254

If I understand the scenario correctly, you are copying the code typed into the textarea into a div next to it, in order to obtain an effect similar to w3schools' "try it." My advice? This is an ineffective way to do what you want to do.

The simplest way I can think of would be to use an iframe, not a div. On submission, with a little back-end code you can make the source code of the iframe be the text in the textarea. There is no way to trick a browser into thinking that a div is a body tag.

Upvotes: 1

benfes
benfes

Reputation: 215

The problem is that body is a registered DOM element, so it will always refer to the body element of the entire document.

What you could try is in your javascript replace body with the element selector that you which to change. E.g.

var html = $(editor.getValue());
$('#outputContainer').html(html.replace('body','#outputContainer'));

This isn't a very elegant solution, however it will quickly do what you are trying to achieve.

Upvotes: 1

Related Questions