Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Stylesheet

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

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

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

Now imagine the following code is like jQuery for CSS...

Getting values from the CSS

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

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

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

Setting values in the CSS

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

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

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

Fairly certain this is not possible...but just a wild stab in the dark!

like image 478
Matthew Layton Avatar asked Jan 08 '14 00:01

Matthew Layton


2 Answers

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

like image 142
Alex Wayne Avatar answered Sep 20 '22 01:09

Alex Wayne


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

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.

like image 23
itsmikem Avatar answered Sep 17 '22 01:09

itsmikem