I've written this code that iterates over all global style sheet rules and stores them in an array/object. I use this dictionary-like object later to change global rules rather than setting styles on individual elements.
Following code breaks in IE8 but works fine in Firefox3.7 and Chrome4.
var allRules;
$(function() {
var fileRules;
allRules = [];
$.each(document.styleSheets, function() {
// get rules for any browser (IE uses rules array)
fileRules = this.cssRules || this.rules;
$.each(fileRules, function() {
allRules[this.selectorText] = this;
});
});
});
I get Invalid procedure call or argument error. When I try to debug it, this code sucessfully iterates through two CSS style sheet files with rules but when the second one's iteration is done, it fails.
I can't seem to find an error in this code.
The problem
After thorough testing I found out that
document.styleSheetsisn't a regular array in IE. That's why it breaks in$.each()call when it reaches the end.If we take a look at jQuery function itself it has a
forloop to iterate over an object that has alengthproperty, falsely believing it's an array.document.styleSheetsdoes havelengthproperty, but it's obviously not an array. So when thisforloop in$.each()is executed:it fails after the last element has been iterated over. As we may see this
forloop doesn't incremention its own but rather increments it while assigning a new value tovalue.We can check this manually as well. Write these two lines in any browser's address bar:
The first one runs fine in all browsers, but the second one fails in IE.
The solution
We have to rewrite the iteration over style sheets