Illusion705
Illusion705

Reputation: 451

Uncaught DOMException: Failed to execute 'addRule' on 'CSSStyleSheet': Cannot access StyleSheet to insertRule

I got the following error when I was working on a project: "Uncaught DOMException: Failed to execute 'addRule' on 'CSSStyleSheet': Cannot access StyleSheet to insertRule"

Could someone help me fix my code, because I'm not sure why I'm getting this error.

The head of my HTML document:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plunder Data Research and Analysis</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP&display=swap" rel="stylesheet">
</head>

The line of JavaScript code that is giving the error:

styleSheet.addRule(".new-plunder-form-username:focus {border: 1.5px solid #75b4d9; box-shadow: 0 0 5px #75b4d9;}");

The styleSheet constant:

const styleSheet = document.styleSheets[0];

I found this similar question on Stack Overflow, but my stylesheets as you can see are already ordered with the stylesheet I'm trying to access first like it said to do.

Upvotes: 2

Views: 2010

Answers (1)

Snow
Snow

Reputation: 4097

Make sure the styles.css exists on your server. If it doesn't, that might be causing it to be inaccessible.

Worst-case, you could create and insert another stylesheet.

const styleSheet = document.createElement('style');
document.head.appendChild(styleSheet);
styleSheet.textContent = ".new-plunder-form-username:focus {border: 1.5px solid #75b4d9; box-shadow: 0 0 5px #75b4d9;}";

Upvotes: 2

Related Questions