Search code examples
javascriptcssgoogle-chromestylesheet

Weird behaviour in Chrome regarding document.styleSheets


I've got this code...

function disableSheets(){
  console.log(document.styleSheets.length);
    var c = document.styleSheets.length;
    for(var i=0;i<c;i++){
      console.log(document.styleSheets[i]);
        if(typeof document.styleSheets[i]!=='undefined' && document.styleSheets[i].href.indexOf('stylezone')!=-1){
          document.styleSheets[i].disabled=true; 
        }
    }
    console.log(document.styleSheets.length);
}

When I run it in Firefox/Firebug it says:

3
StyleSheet
StyleSheet
StyleSheet
3

When I run it in Chrome/Developer Tools it says:

3
CSSStyleSheet
CSSStyleSheet
undefined
1

So my questions are:

  1. Why would it say there are 3 stylesheets if the 3rd is undefined?
  2. How did I lose 2 stylesheets by the end of that loop?
  3. What happened to the 3rd sheet?

At the top of my HTML I have the 3 <link>s, linking the 3 stylesheets, and then immediately after that I call disableSheets().


Solution

  • Apparently, style sheets are removed from the document.styleSheets object (Chrome), when disabled.

    Your code does actually read the first and third styleSheet:

    An overview:

    • 3 stylesheets: A, B, C
    • var c = document.styleSheets.length;
    • Loop, i=0
    • i=0, Select styleSheet[i] = StyleSheet A
      2 stylesheets left: B, C
    • Loop, i=1
    • i=1, Select styleSheet[i] = StyleSheet C
      1 stylesheet left: B
    • Loop, i=2
    • i=2, Select styleSheet[i] = undefined
    • Loop i<3 = break
    • Console.log(document.styleSheets.length) = 1 (Stylesheet B)

    To get your code work, reverse the loop:

     for(var i=c-1; i>=0; i--){
    

    Note: Initialise i at c-1! JavaScript array-like objects' indices are zero-based.