cssjs

Javascript to modify CSS rules, not of elements, but actual rules which in turn affect elements.

by ubershmekel

HTML

<h1>Mouse hover here to add styles</h1>
<p>P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text P example with a lot of text</p>
<p>Another P example</p>
<div class="theclass">A div with "theclass" as its class</div>
<div id="unique">this is a div with an id</div>

JavaScript

$(function() {
    console.log(getCSSRule('p'));  // returns false
    console.log(getCSSRule('h1')); // returns false
    console.log(getCSSRule('.theclass')); // returns false
    addCSSRule('.theclass');
    console.log(getCSSRule('.theclass')); // returns a CSSStyleRule object
    
    $('body').on('mouseover', function() {
        getCSSRule('.theclass').style.color = '#f00';
        addCSSRule('p').style.color = '#0f0';
        addCSSRule('h1').style.color = '#00f';
        addCSSRule('#unique').style.display = 'none';
    });    
});

function getCSSRule(ruleName, deleteFlag) {               // Return requested style obejct
   ruleName=ruleName.toLowerCase();                       // Convert test string to lower case.
   if (document.styleSheets) {                            // If browser can play with stylesheets
      for (var i=0; i<document.styleSheets.length; i++) { // For each stylesheet
         var styleSheet=document.styleSheets[i];          // Get the current Stylesheet
         var ii=0;                                        // Initialize subCounter.
         var cssRule=false;                               // Initialize cssRule. 
         do {                                             // For each rule in stylesheet
            if (styleSheet.cssRules) {                    // Browser uses cssRules?
               cssRule = styleSheet.cssRules[ii];         // Yes --Mozilla Style
            } else {                                      // Browser usses rules?
               cssRule = styleSheet.rules[ii];            // Yes IE style. 
            }                                             // End IE check.
            if (cssRule)  {                               // If we found a rule...
               if (cssRule.selectorText.toLowerCase()==ruleName) { //  match ruleName?
                  if (deleteFlag=='delete') {             // Yes.  Are we deleteing?
                     if (styleSheet.cssRules) {           // Yes, deleting...
         ...