Invalid procedure call or argument repeated when using document.styleSheets using $ .each ()

I wrote this code that iterates through all the rules of the rules table and stores them in an array / object. I will use this dictionary-like object later to change global rules, rather than set styles for individual elements.

After 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 an error Invalid procedure call or argument. When I try to debug it, this code successfully iterates through two CSS stylesheet files with rules, but when the second iteration is complete, it fails.

I can not find the error in this code.

+3
3

, document.styleSheets IE. $.each(), .

jQuery, for length, . document.styleSheets length, , , . , for $.each() :

for (var value = object[0];
     i < length && callback.call( value, i, value ) !== false;
     value = object[++i]){}

, . , for i , value.

. :

javascript:var a=[1,2,3];alert(a[3]);void(0);
javascript:alert(document.styleSheets[document.styleSheets.length]);void(0);

, IE.

var allRules;

$(function() {
    var fileRules;
    allRules = {};
    // can't use $.each() over document.styleSheets because it not an array in IE
    for (var i = 0; i < document.styleSheets.length; i++)
    {
        fileRules = document.styleSheets[i].cssRules || document.styleSheets[i].rules;
        $.each(fileRules, function() {
            allRules[this.selectorText] = this;
        });
    }
});
+13

, ? , , - .

0

code true:

var fileRules;
(function ($) {
    allRules = {};
    for (var i = 0; i < document.styleSheets.length; i++) {
        fileRules = document.styleSheets[i].cssRules || document.styleSheets[i].rules;
        $.each(fileRules, function () {
            allRules[this.selectorText] = this;
        })(jQuery);
    }
});
-2
source

Source: https://habr.com/ru/post/1733377/


All Articles