0

I'm trying to understand how the jquery pertaining to modifying stylesheets works by understanding how to do it with vanilla javascript, but there isn't a lot of resources on the subject that I can find. I already checked the stack over flow page on the subject but I cant figure out what I'm doing wrong.

I have a simple html page and a simple style sheet, with the javascript in the html page in a script tag

html page

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
         <link rel="stylesheet" href="main.css">
    </head>
    <body>
        <div class="parent"></div>
        <script>
            let parent=document.getElementsByClassName('parent')[0];
            for(let i=0; i<10;i++){
                let child=document.createElement('div');
                let id= "i"+ i.toString();
                child.setAttribute("id",id);
                parent.appendChild(child);
            }
        </script>
    </body>
</html>

style sheet

        body{
            background-color: lightblue;
        }
        .parent{
            display:flex;
            flex-wrap: wrap;
            flex-direction: column;
        }
        .parent div{
            margin: 5px;
            width: 50px;
            height: 50px;
            background-color: white;
        }

console commands

when I style to pull up the stylesheet object, in the console I get the object aka the stylesheet but the cssRules property is set to null, with none of the rules in the style sheet in it. I cant figure out as to why this is.

for example

 document.styleSheets //returns StyleSheetList {0: CSSStyleSheet, length: 1}

document.styleSheets[0] /*returns CSSStyleSheet {ownerRule: null, cssRules: 
   null, rules: null, type: "text/css", href:
   "file:///C:/Users/brand/Documents/test/main.css"…}*/
Brandon
  • 1,099
  • 1
  • 9
  • 14
  • 2
    Can't reproduce, works fine for me. –  Jan 06 '17 at 22:16
  • 1
    Actually: Firefox always shows the rules, Chrome indeed doesn't if the file is opened via file:///, I had to open it via web server for it to work –  Jan 06 '17 at 22:21
  • @ChrisG, you can post it as answer. So, for offline testing you will have to install XAMP, Wamp...or something similar... – sinisake Jan 06 '17 at 22:26

2 Answers2

1

Access to stylesheet data is subject to the Same Origin Policy. Most browsers consider any file:/// URL to be on a different origin.

You need to be using HTTP or HTTPS to access the document, and have the stylesheet on the same origin.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

The issue seems to be related to this: cssRules/rules are null in Chrome

The solution is to look at the site via a web server like Apache / XAMPP.

Community
  • 1
  • 1