1

I tried to add style link in an HTML page and insert rule

let linklength = document.head.querySelectorAll("link[rel=stylesheet]").length;
let style = document.createElement("link");
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", "./test.css");
document.head.appendChild(style);
let myStyle = document.styleSheets[linklength];
myStyle.insertRule(".red{color:red}");

But myStyle is undefined and new style didn't add in document.styleSheets. I could solve as follows

let linklength = document.head.querySelectorAll("link[rel=stylesheet]").length;
let style = document.createElement("link");
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", "./test.css");
document.head.appendChild(style);
setTimeout(() => {
    let myStyle = document.styleSheets[linklength];
    myStyle.insertRule(".red{color:red}");
}, 5000);

but I want to insert rule immediately. I've already set timeout 0 milisecond but it didn't work.

webelf000
  • 147
  • 9
  • I'm not very familiar with loading CSS this way, but I'm guessing your CSS file is not finished downloading before your code attempts to insert the additional rule, which means you need a delay that permits the download to complete before you can add rules to the downloaded stylesheet. I would recommend against doing your CSS loading this way. – Marc Jul 31 '20 at 20:34
  • I'm not sure the purpose of attaching to an existing stylesheet, but this will accomplish the goal of creating classes with javascript [How to dynamically create CSS class in JavaScript and apply?](https://stackoverflow.com/questions/1720320/how-to-dynamically-create-css-class-in-javascript-and-apply) – imvain2 Jul 31 '20 at 20:45

1 Answers1

1

The problem is it takes time to download and apply the new stylesheet that you've just added, you need to listen on load event of the new link so you'll able to do something when the new stylesheet loaded.
Working Example :

const link = document.createElement("link");
link.href = "https://code.jquery.com/jquery-3.5.1.min.js"; //your url
console.log(document.styleSheets.length);
link.rel = "stylesheet";
document.head.appendChild(link);
link.addEventListener("load",yourHandler);
function yourHandler(){
   console.log(document.styleSheets.length);
   link.removeEventListener("load",yourHandler);
}
Shawn Vn
  • 297
  • 1
  • 14