main
js 50 lines 1.47 KB
Raw
1 // Create and keep a reference to a dynamic stylesheet for runtime CSS changes
2 let dynamicStyleSheet;
3 {
4 const style = document.createElement("style");
5 style.appendChild(document.createTextNode(""));
6 document.head.appendChild(style);
7 dynamicStyleSheet = style.sheet;
8 }
9
10 export function toggleCssProperty(selector, property, value) {
11 // Get the stylesheet that contains the class
12 const styleSheets = document.styleSheets;
13
14 // Iterate through all stylesheets to find the class
15 for (let i = 0; i < styleSheets.length; i++) {
16 const styleSheet = styleSheets[i];
17 let rules;
18 try {
19 rules = styleSheet.cssRules || styleSheet.rules;
20 } catch (e) {
21 // Skip stylesheets we cannot access due to CORS/security restrictions
22 continue;
23 }
24 if (!rules) continue;
25
26 for (let j = 0; j < rules.length; j++) {
27 const rule = rules[j];
28 if (rule.selectorText == selector) {
29 _applyCssToRule(rule, property, value);
30 return;
31 }
32 }
33 }
34 // If not found, add it to the dynamic stylesheet
35 const ruleIndex = dynamicStyleSheet.insertRule(
36 `${selector} {}`,
37 dynamicStyleSheet.cssRules.length
38 );
39 const rule = dynamicStyleSheet.cssRules[ruleIndex];
40 _applyCssToRule(rule, property, value);
41 }
42
43 // Helper to apply/remove a CSS property on a rule
44 function _applyCssToRule(rule, property, value) {
45 if (value === undefined) {
46 rule.style.removeProperty(property);
47 } else {
48 rule.style.setProperty(property, value);
49 }
50 }