How to apply custom css code introduced in textarea using javascript

Viewed 218

I am making sites that can be edited using CSS selectors. But now I have to make an advanced section where the user can put their CSS code in a textarea to edit the styles manually for example

.anyClass {
  text-align: center;
  color: blue;
}

#anyId {
  text-align: center;
  color: red;
}

.anyDiv {
  text-align: center;
  color: yellow;
}

.spacer-line border-primary{
  text-align: center;
  color: red;
  border-color: blue;
}

these IDs and classes are only examples, the script must accept whatever data is entered, for example .columns-mobile, .custom-button, etc

If I have the entered data as string in javascript, how can I add this to the page for update the css style?

The best way would be to insert all the code to the header of the page?

1 Answers

I assume you added id="textar" to the textarea

var textArea = document.getElementById("textar");

//To add classes:
textArea.classList.add("className");

//To remove classes:
textArea.classList.remove("className");

Where, classname is the class which you dynamically need to add.

If you want to add or remove classes as the user types in the textarea, you can do:

textArea.addEventListener('change', () => {
    //If you want to add
    textArea.classList.add(textArea.value);

    //Similarly for remove
});
Related