Add CSS Rule Via JQuery For Future Created Elements


Answer :

This should work:

var style = $('<style>.class { background-color: blue; }</style>'); $('html > head').append(style); 

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.


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'))); 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable