Skip to content Skip to sidebar Skip to footer

Can I Programmatically Traverse A Css Stylesheet?

jQuery provides a nice, neat way to traverse the DOM...what I'm looking for is a way to traverse a stylesheet, getting and setting attributes for the defined styles. Example Styles

Solution 1:

I think you can, but the interface is more obtuse than you probably want.

document.styleSheets returns a StyleSheetList object that seems to behave in an array like way.

So document.styleSheets[0] returns a CSSStyleSheet object. Look to have lots of ways to analyze it's content. And each CSSStyleSheet has a cssRules property which returns a CSSRuleList.

And you can traverse the docs on the various types return by the DOM api from there yourself: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet

Solution 2:

I just found a way to look through all of your style sheets, using jquery initially:

I have three stylesheets on my page, so first, I must identify the one I need to manipulate and I gave it an id: <style id="localRules">...</style>

Then, I use jQuery to initially find the id'd stylesheet I'm planning to change:

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 onif(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;               
     }
}

Hope this is helpful...it worked for me, but took a while to figure it out, especially because ownerNode is something I've never heard of before.

Post a Comment for "Can I Programmatically Traverse A Css Stylesheet?"