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
1 Asked on February 9, 2021 by shkiperdesna
2 Asked on February 9, 2021 by charlessssss
2 Asked on February 9, 2021 by bha
3 Asked on February 9, 2021 by user3591442
2 Asked on February 9, 2021 by seyed-hosseini
1 Asked on February 9, 2021 by goncalo-condeco
0 Asked on February 9, 2021 by cng-hong
1 Asked on February 8, 2021 by shivam-kumar
1 Asked on February 8, 2021 by hamza-sayyid
0 Asked on February 8, 2021 by kauii8
2 Asked on February 8, 2021 by sumi
2 Asked on February 8, 2021 by gilly4297
2 Asked on February 8, 2021 by leem-fin
1 Asked on February 8, 2021 by gustavo-reis
4 Asked on February 8, 2021 by papemoussa
1 Asked on February 8, 2021 by stefan-tredoux
2 Asked on February 8, 2021 by soscodehelp
1 Asked on February 8, 2021 by edison
Get help from others!
Recent Questions
Recent Answers
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP