Add CSS rule via jQuery for future created elements
Solution 1:
This should work:
var style = $('<style>.class { background-color: blue; }</style>');
$('html > head').append(style);
Solution 2:
When you plan to remove elements from the DOM to re-insert them later, then use .detach() instead of .remove()
.
Using .detach()
will preserve your CSS when re-inserting later. From the documentation:
The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.
Solution 3:
Here is some JavaScript code I wrote before to let me add, remove and edit CSS:
function CSS(sheet) {
if (sheet.constructor.name === 'CSSStyleSheet' )
this.sheet = sheet;
else if (sheet.constructor.name === 'HTMLStyleElement')
this.sheet = sheet.sheet;
else
throw new TypeError(sheet + ' is not a StyleSheet');
}
CSS.prototype = {
constructor: CSS,
add: function( cssText ) {
return this.sheet.insertRule(cssText, this.sheet.cssRules.length);
},
del: function(index) {
return this.sheet.deleteRule(index);
},
edit: function( index, cssText) {
var i;
if( index < 0 )
index = 0;
if( index >= this.sheet.cssRules.length )
return this.add(cssText);
i = this.sheet.insertRule(cssText, index);
if (i === index)
this.sheet.deleteRule(i + 1);
return i;
}
};
And then if a new stylesheet is required, construct as
var myCss = new CSS(document.head.appendChild( document.createElement('style')));