2

Possible Duplicate:
How to dynamically create CSS class in JavaScript and apply?

I want to create css classes depending upon what user has specified a width in a textfield. I know I can do it using inline styles, but I want to avoid it as there are many properties to be taken care of. In this question "width" is just an example.

For eg: if user specifies width as "20" then I want -

.w20 {width:20px}

if user specifies 21 then I want

.w21 {width:21px}

and so on...

FIDDLE

Thanks.

Community
  • 1
  • 1
Ashwin
  • 12,081
  • 22
  • 83
  • 117

3 Answers3

2

You can use document.stylesheets to add css rules dynamically directly to your stylesheets.

styleSheet = document.styleSheets[0];
// check for undefined could make sense here
styleSheet.addRule(selector, style);

insertRule Doc
addRule Doc

or create a new style-element

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.class { rules }';
document.getElementsByTagName('head')[0].appendChild(style);
Christoph
  • 50,121
  • 21
  • 99
  • 128
0

You could try using document.stylesheets to add css dynamically to your stylesheets.

styleSheet = document.styleSheets[0];
styleSheet.addRule(selector, style);

You could also use inline styles (id recommend this approach).

You can change the width of an element using JavaScript like this.

elem.style.width = "100px";

And using jQuery

$("#selector").css("width", "100px");
Undefined
  • 11,234
  • 5
  • 37
  • 62
  • Thanks, but I knew the inline method and I have mentioned in question that I do not want to do that. – Ashwin Jul 18 '12 at 07:53
0

See here to lean how to add css rules in runtime.

My opinion: with best software design, you will never need to do that.

Community
  • 1
  • 1
darksky
  • 1,955
  • 16
  • 28