Stack Overflow Asked by webelf000 on August 5, 2020
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.
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);
}
Correct answer by Shawn Vn on August 5, 2020
4 Asked on February 4, 2021 by michaelstackquestion
2 Asked on February 4, 2021 by ajij-shaikh
2 Asked on February 4, 2021 by akrilmokus
2 Asked on February 4, 2021 by fahad-munir
2 Asked on February 4, 2021 by fadhil-kemal
android app bundle dart flutter flutter build flutter channel
1 Asked on February 4, 2021 by majid
4 Asked on February 4, 2021 by maggie-blanton
1 Asked on February 3, 2021 by rabie_alkholi
1 Asked on February 3, 2021 by jaysmito-mukherjee
2 Asked on February 3, 2021 by nmdvdisha
2 Asked on February 3, 2021 by luke-prior
1 Asked on February 3, 2021 by chetang
background process beanstalkd deployment production ruby on rails
2 Asked on February 3, 2021 by sachin
2 Asked on February 3, 2021 by mrduk
3 Asked on February 3, 2021 by nishan-gadtaula
3 Asked on February 3, 2021 by askumang
0 Asked on February 3, 2021 by vjswamy
Get help from others!
Recent Questions
Recent Answers
© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir