using javascript to edit css classes


Ever wanted to change the style for a lot of elements in an html document in realtime? I have. Its not too hard either, but just to make life easier, I wrote a quickie prototype-styled stylesheet element accessor function.

function $S(selname) { var rule = null; var sheets = document.styleSheets; for (i=0; i<sheets.length && rule == null; i++) { var rules = sheets[i].rules for (j=0; j<rules.length && rule == null; j++) { if (rules[j].selectorText == selname) { rule = rules[j]; } } } return rule; }
Now someone else out there probably has a better version of this function (and has probably ensured that it worked versus more browsers than I have [I only tested firefox, ie and safari]), but it works. Its not the fastest either, note the loop over all stylesheets and their elements to find the targets. Hopefully this will help someone, as when I googled (yes the term has entered my lexicon) for information on how to update a stylesheet using javascript.

A quick example of usage:

var mystyle = $('.onespiffyclass'); mystyle.style.backgroundColor = 'yellow'; // wewt, we should have a yellow bg for all elements using onespiffyclass as their style class