Question

When trying to iterate over document.styleSheets it doesn't go over every attribute.


This results when console logging document.styleSheets

StyleSheetList {0: CSSStyleSheet, 1: CSSStyleSheet, length: 2, item: function}
    0: CSSStyleSheet
    1: CSSStyleSheet
    2: CSSStyleSheet
    length: 3



And iterating over these attributes gives me

0 elementLoader.js:11
1 elementLoader.js:11
length elementLoader.js:11



It seems like the last stylesheet is not enumerable but I have no idea why and it happens to be the one I wish to look at.


Any ideas?



The code I'm running:

var styleSheets = document.styleSheets;
console.log(styleSheets);
for (var i in styleSheets)
{
    console.log(i);
}

In this example printing document.styleSheets[2] returns null.



SOLUTION:
Turn's out that angular was pulling some trickery. By loading the code within a directive instead of a script tag I was able to iterate all of the style sheets. What a weird error.

Was it helpful?

Solution 3

Turn's out that angular was pulling some trickery. By loading the code within a directive instead of a script tag I was able to iterate all

OTHER TIPS

Are you trying to do this instead:

var styleSheets = document.styleSheets;
console.log(styleSheets);
for (var i in styleSheets)
{
    console.log(styleSheets[i]); // Log stylesheet instead of index
}

Let's break down what you have shown to us so far.

Part1.

StyleSheetList {0: CSSStyleSheet, 1: CSSStyleSheet, length: 2, item: function}

The above appears to be what you are seeing in your console.log, you are then expanding this object to see the content and then you see (as @Barmar suggested).

    0: CSSStyleSheet
    1: CSSStyleSheet
    2: CSSStyleSheet
    length: 3

This suggests that you have loaded a stylesheet after the original logging.

Part 2

You use enumeration rather than iteration on the StyleSheetList and you posted a copy-paste

0 elementLoader.js:11
1 elementLoader.js:11
length elementLoader.js:11

Which needs to be cleaned up as the elementLoader.js:11 is part of the copy-paste and not the actual log, and you have.

0
1
length

Which matches what was first logged before a later stylesheet was loaded.

Note that you see the length property name as it is ennumerable, you wouldn't see this is you use iteration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top