Editable CSS by editing text on textarea?

Viewed 377

How can I make a textarea which has the stylesheet of the web page inside it?

I want to make a web page which a user can customize its <style> settings by editing text inside a textarea.

Here's what I have done so far; inside the <textarea> of this code snippet is the editable text which I intend to make it function as the web page's stylesheet, but I'm not sure how to make it work.

I did many web search looking for solutions, but could not find useful help regarding this particular function. Any help will be appreciated.

function myFunction() {
  document.getElementsByTagName("style")[0].innerHTML = "document.getElementById('input').value;";
}
<p>sample text</p>
<textarea id="input" oninput="myFunction()" rows="5">p {
font-family: monospace;
font-size: 15px;
}
</textarea>

1 Answers

You're very close, but your code has 2 problems.

  1. document.getElementsByTagName returns an array, so you need to select the first element of the array using [0].
  2. You are not actually getting the input element, you're just using a string of the code you want to run (i.e. you want to run the code document.getElementById('input').value but you've put quotes around it, which turns it into a string).

This updated version should work:

function myFunction() {
  document.getElementsByTagName("style")[0].innerHTML = document.getElementById('input').value;
}
<p>sample text</p>
<textarea id="input" oninput="myFunction()" rows="5">html {
font-family: monospace;
font-size: 15px;
}
</textarea>

Related