I am having trouble figuring out why .cssRules
and .rules
won't work in my simplistic color generator project.
I have a <link>
element to link my external CSS file:
<link href="ColorGenerator.css" type="text/css" rel="stylesheet">
And a <script>
element to link my external JS file before the </html>
element:
<script src="ColorGenerator.js" type="text/javascript"></script>
I then have this in my CSS file:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#body {
background: #E1E1F4;
}
And this on the JS file:
const mySheet = document.styleSheets[0];
const body = document.getElementById("body");
body.onkeydown = function(e) {
if (e.keyCode == 32) {
mySheet.rules[0].style.background = "#ffa500";
}
};
But when I press space(e.keyCode == 32
) nothing happens, so then I open the developer tools in Chrome and I get this error message:
Uncaught DOMException: Failed to read the 'rules' property from 'CSSStyleSheet': Cannot access rules at HTMLBodyElement.body.onkeydown
I'm not sure if Chrome just doesn't support it or if I have a failure in my code, eitherway I truly appreciate any help.
As of Chrome 64, new CORS rules are enforced for stylesheets. You'll need to use a local development server to do local testing of functionality that depends on the CSS Object Model. For details, see Cannot access cssRules from local css file in Chrome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With