views:

62

answers:

1

I tried to use $.cssRule() plugin and found that it makes it inconvenient to debug those rules in FireBug because each rule appears to be attached to every css file loaded on my page and consequently defined many times.

Source code shows that it does that on purpose inside that for loop: for(var i = 0; i < document.styleSheets.length; i++) ... insertRule ...

Why can't it add new own style-sheet and then add rules to it ?

If it's necessary for rules prioritization then why not shuffle style sheets ?

I noticed the same issue here so unless those 2 places come from same source which had a bug, I wonder why it is necessary to do it that way.

+1  A: 

I think I remember why I did like this in the answer you have linked to. I'm not just adding a new rule, I'm adding a new rule to an existing declaration. So I had to look up every stylesheet in order to find that declaration. Now, the best optimization that I can come up with right now, is to read the styleSheets in reverse order, and break the loop after the first encounter of that selectorText. This way, you modify just one stylesheet, the one with the highest precedence.

var ss = document.styleSheets;

for (var i=ss.length-1; i>=0; i--) {
    var rules = ss[i].cssRules || ss[i].rules;

    for (var j=0; j<rules.length; j++) {
        if (rules[j].selectorText === ".classname") {
            rules[j].style.color = "green";
            break;
        }
    }
}

Anyway, this assumes that the order of the stylesheet objects in the collection is the inverse of the order of precedence, which I believe it is.

Ionuț G. Stan
Why do you have to check and match existing selectors ? Why not just add new one ? Is there a requirement to keep unique list of selectors ? Since selectors '.classname' and 'body .classname' will not match with your method anyway and there is no visible harm in creating 2 rules with same selector under different style-sheets, what is the point in comparing among all stylesheets ? Why not create new own style-sheet, put it into highest priority position and maintain selector uniqueness only there just to allow changes of previously defined with that method rules ?
alpav
That sounds better. Just do whatever you see fit, I did not intend to have a perfect or exhaustive solution. Anyway, watch for cross-browser compatibility.
Ionuț G. Stan
That's what I was wondering if my solution will work because jQuery.cssRule does it the same way as you do and jQuery.cssRule purpose is cross-browser compatibility, so I suspect that my solution is wrong somewhere.
alpav