Can I programmatically traverse a CSS stylesheet?
css, html, javascript, jquery, stylesheet
Solution
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.
Problem
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!