Can I programmatically traverse the CSS stylesheet?

jQuery provides a nice, neat way of traversing the DOM ... what I'm looking for is a way of going through a stylesheet, getting and setting attributes for certain styles.

Style sheet example

div {
    background: #FF0000;
    display: block;
}

.style {
    color: #00AA00;
    font-family: Verdana;
}

html body > nav.menu {
    list-style: none;
}

Now imagine the following code is similar to jQuery for CSS ...

Getting Values ​​from CSS

$("div").attr("background");
//returns #FF0000;

$(".style").attr("color");
// returns #00AA00;

$("html body > nav.menu").attr("color");
// returns undefined;

Setting Values ​​in CSS

$("div").attr("background", "#0000FF");

$(".style").attr("color", "#CDFF4E");

$("html body > nav.menu").attr("color", "#FFFFFF");

Pretty sure it's impossible ... but just a wild blow in the dark!

+4
source share
2 answers

I just found a way to view all your stylesheets using jquery first:

, -, , , : <style id="localRules">...</style>

jQuery, id'd, :

var sheetToChange = "localRules";
var sheets = $(document.styleSheets); 
// loop through all the stylesheets    
for (var thisSheet=0;thisSheet<sheets.length;thisSheet++){
     // find the right stylesheet to work on
     if(sheets[thisSheet].ownerNode.id == sheetToChange ){
          // cross browser referencing of css rules:
          var ruleSet = sheets[thisSheet].cssRules || sheets[thisSheet].rules;
          for (var thisRule=0;thisRule<ruleSet.length;thisRule++){
               // traverse in that style sheet for the rule you want to change, in this case, body:
               if(ruleSet[thisRule].selectorText == "body"){
                    ruleSet[thisRule].style.cursor = "pointer";
               }
           }
           break;               
     }
}

, ... , , , , ownerNode - , .

+1

, , , , , .

document.styleSheets StyleSheetList, , -, .

, document.styleSheets[0] CSSStyleSheet. , . CSSStyleSheet cssRules, CSSRuleList.

, DOM api : https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet

+6

All Articles