10

I want to create a new style, not just alter the style attribute of an element. Here's some example code to demonstrate the problem:

//Create 1st element
var element1 = $('<div />').text('element1').addClass('blue');
$('body').append(element1);

//Set some css for all elements with the blue class
$('.blue').css('background-color', 'blue');

//Create 2nd element, it won't have the css applied because it wasn't around when the css was set
var element2 = $('<div />').text('element2').addClass('blue');
$('body').append(element2);​

In the code above the 2nd element does not have the same style as the 1st. What I would like is to be able to set the css on a className for all future elements.

JSFiddle

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
Drahcir
  • 11,772
  • 24
  • 86
  • 128

2 Answers2

19

You could create a new stylesheet and append this to the head:

$("<style type='text/css'> .blue{ background-color:blue;} </style>").appendTo("head");

See Demo: http://jsfiddle.net/YenN4/2/

Curtis
  • 101,612
  • 66
  • 270
  • 352
5

Demo: http://jsfiddle.net/T6KEW/

$('<style>').text('.blue { background: blue }').appendTo('head');

$('<div>').text('element1').addClass('blue').appendTo('body');
$('<div>').text('element2').addClass('blue').appendTo('body');​
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79