Shimul
Shimul

Reputation: 468

How to write CSS styles in a CSS files using JS?

Suppose I have a CSS file custom_style.css and a HTML file custom_render.html.

custom_render.html contains some input field to take input from user and than generates CSS styles based on those input.

Now I want to store those generated CSS styles in a CSS file called custom_style.css [that is located in my projects root directory], so that I can show the users a preview/output of their selections.

After googling I got a way to store those generated CSS in the same file [custom_render.html] using JavaScript, but I want to store them in custom_style.css.

Can anyone tell me how can I write CSS Styles in CSS files using JavaScript or other JavaScript framework.
- Thanks

Upvotes: 1

Views: 2336

Answers (3)

YOHANNES MOJO
YOHANNES MOJO

Reputation: 1

insertRule(rule, index) This will inserts a new rule to the stylesheet, where the parameter "rule" is a string containing the entire rule to add (ie: #myid{color: red; border: 1px solid black}), and "index", an integer specifying the position within cssRules[] to insert the new rule.

document.styleSheets[0].insertRule("p{font-size: 20px;}", 0) //add new rule to start of stylesheet

Upvotes: 0

m87
m87

Reputation: 4523

simple... (assuming this is what you trying to achieve)

var elem = document.getElementsByClassName('target_class');
// should use for loop to assign click event to each element containing this class
elem[0].onclick = function() {
  elem[0].style.background = 'green';
  elem[0].style.opacity = '0.2';
}
<div class="target_class" style="width: 200px; height: 200px; background: red"></div>

Upvotes: 0

RATKNUKKL
RATKNUKKL

Reputation: 126

Well, you can modify the parameters of objects in your stylesheets. For example:

document.styleSheets[i].rules[j].style.marginTop = "100px";

i being the number corresponding to the sheet you want to edit

and

j being which element rule you want to change the parameter for.

In this case I used marginTop as a paramater and 100px as a value but it could be whatever valid CSS you would like.

Upvotes: 5

Related Questions