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.