$(document)[0].styleSheets[styleSheetIndex].insertRule(rule, lineIndex);
styleSheetIndex is the index value that corresponds to the order that you uploaded to the <head> file (for example, 0 is the first file, 1 is the next, etc., if there is only one CSS file, use 0),
rule is a CSS rule in a text string. For example: "body { display:none; }" .
lineIndex - line number in this file. To get the last line number, use $(document)[0].styleSheets[styleSheetIndex].cssRules.length . Just console.log this styleSheet object got some interesting properties / methods.
Since CSS is a cascade, any rule that you try to insert for this selector, you can simply add to the bottom of the CSS file and overwrite everything that was written when the page was loaded.
In some browsers, after manipulating the CSS file, you need to force the CSS to βredrawβ by calling some kind of meaningless method in the JS DOM, for example document.offsetHeight (it is abstracted as a DOM property, not a method, so you don't need to use "()") - just adding that after your CSSOM manipulation causes the page to redraw in older browsers.
So here is an example:
var stylesheet = $(document)[0].styleSheets[0]; stylesheet.insertRule('body { display:none; }', stylesheet.cssRules.length);
benny Jul 27 '15 at 18:11 2015-07-27 18:11
source share