简体   繁体   中英

Setting the CSS of an html element with text entered by the user

My page has two textareas and a div. One textarea is for the user to enter html and the other is for entering css. When a button is clicked I will call a javascript function to display the css and html inside the div.

 function handleLaunch() { var div = document.getElementById('pane'); var html = document.getElementById('h'); var css = document.getElementById('c'); div.innerHTML = html.value; // This line obviously doesn't work div.style = css.value; } 
 <body> <textarea id="c" placeholder="CSS code here..." rows="10" cols="50"></textarea> <div id="pane"> </div> <br> <textarea id="h" placeholder="Html code here..." rows="10" cols="50"></textarea> <br> <button type="button" onclick="handleLaunch()">Launch</button> 

Now, how to set the css to the text ?

EDIT: I should have mentioned that I want to be able to put something like .classExample{text-align:center} in the css textarea and have it apply.

Yes, @adeneo answer works, this snippet shows it. Enter color: red; for example as CSS, and any text as HTML...

 function handleLaunch() { var div = document.getElementById('pane'); var html = document.getElementById('h'); var css = document.getElementById('c'); div.innerHTML = html.value; div.style.cssText = css.value; } 
 <body> <textarea id="c" placeholder="CSS code here..." rows="10" cols="50"></textarea> <div id="pane"> </div> <br> <textarea id="h" placeholder="Html code here..." rows="10" cols="50"></textarea> <br> <button type="button" onclick="handleLaunch()">Launch</button> 

Assuming that you are defining css properties along with selectors, for example you css text is like

div{
    background:red;
}
.someClass{
    font-size:12px;
}

and your html looks like

<div>DIV content</div>
<span class="someClass"> Content in someClass</span>

You can add the html as div.innerHTML = html.value;

But for adding the css to your page you will have to do the following

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = document.getElementById('c').value;
document.getElementsByTagName('head')[0].appendChild(style)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM