Faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

Entry

I want to change a whole group of style classes - how can I use wildcards or regexps?

Apr 9th, 2008 20:21
ha mo, Dave Clark, Mark,


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mark,
You can't, really.  Wildcards and Regular Expressions cannot directly 
operate on multiple properties of an object -- particularly multiple 
lower-level properties of a parent object such as the StyleSheet 
object.  If I knew more about what you specifically needed to do, I 
could probably come up with something fancy.
For now, though, you would need to iterate through the list of 
properties and perform the change operation one at a time.  This 
function will help you out with manipulating StyleSheets:
function findCssRule(selectorText)
{ // if selectText found, returns array of rule index, rule object, 
and sheet object
    var rules, sheets = document.styleSheets;
    var r, rlen, s, slen = sheets.length;
    for(s=0; s<slen; ++s)
    {
        rules = (sheets[s].rules) ? sheets[s].rules : sheets
[s].cssRules;
        rlen = rules.length;
        for(r=0; r<rlen; ++r)
        {
            if(rules[r].selectorText == selectorText)
            {
                return [r, rules[r], sheets[s]];
            }
        }
    }
    return null;
}
Note, though, that most browsers permit the wholesale extraction and 
replacement of a STYLE (rule) object's properties using a STRING 
operation.  Thus, it is conceivable you could extract the properties 
as a string, use a Regular Expression to modify that string, and then 
replace all properties at once.
The following is an example using the above function to both reference 
a rule object's properties as a string (cssText) and to add a new 
stylesheet rule which is a copy of a current stylesheet rule:
if(ss = findCssRule('.child1'))
{
    if(ss[2].rules) { // IE
        ss[2].addRule(".child2", ss[1].style.cssText);
    } else {          // others
        ss[2].insertRule(".child2 { "+ss[1].style.cssText+" }", ss
[2].rules.length);
    }
} else {
    alert("Stylesheet rule class name 'child1' is not found.");
    return false;
}
Take care,
Dave Clark
www.DaveClarkConsulting.com
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
http://www.businessian.com
http://www.healthinhealth.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com