0

I want to have a better CSS variable control through JavaScript, which requires to operate on a CSSRule object.

Here's the JavaScript code of 2 ways to get it:

// get from the CSSStyleSheet of a <style> element
document.getElementsByTag('style')[0].sheet.rules;
// direct way
document.styleSheets[0].rules;

I've written the CSS in a file, so I have to get it through a element.

However, I found that you can only get a CSSStyleSheet object with a null CSSRule from elements.

link_ele.sheet.rules;  // null

I'm st(f)ucked.

Console output

// btw i've tried this method, but it's just ain't workin' (returns an empty array), thx for tellin' tho @SamuilPetrov

Nianyi Wang
  • 712
  • 6
  • 13
  • 1
    Iterate through the `document.styleSheets` collection until you find one with the appropriate `href` property? – Phylogenesis Aug 25 '17 at 12:06
  • @Phylogenesis nope, won't work, still returns a CSSStyleSheet with a null CSSRule. X-| – Nianyi Wang Aug 25 '17 at 12:11
  • So reverse it and extract the rules by looking up in the whole stylesheet (I doubt it will be significantly slower performance-wise so it's ok): https://stackoverflow.com/a/22638396/4108884 or https://stackoverflow.com/a/2953122/4108884 – Samuil Petrov Aug 25 '17 at 12:20
  • @SamuilPetrov this one still requires to get the 'rules' attribute, which is already known not working. – Nianyi Wang Aug 25 '17 at 12:44
  • No, this is a different rules object, it is the rules property of a global stylesheet object not of a single node element. And I made several tests and it is correctly populated. P.S: It's what @Phylogenesis suggested as well. – Samuil Petrov Aug 25 '17 at 12:53
  • @SamuilPetrov dude... I've tried it in my broswer – Nianyi Wang Aug 25 '17 at 14:39
  • Then something else is messing with your code cause I have tried it on several projects and on google's website as well and it works fine and obviously did for a lot of people in the linked thread. – Samuil Petrov Aug 25 '17 at 15:13
  • @SamuilPetrov hey checkout the screenshot I've added – Nianyi Wang Aug 25 '17 at 15:22

1 Answers1

0

I've found the solution for this situation: You can simply overwrite the style sheet with a created element.

let style = { };
let setCSSVariable = (name, value) => style.rules.setProperty('--' + name, value);
document.addEventListener('DOMContentLoaded', function() {
    style.element = document.createElement('style');
    document.head.appendChild(style.element);

    style.sheet = style.element.sheet;
    style.sheet.insertRule(/* CSS selector */);

    style.rules = style.sheet.cssRules[0].style;
});
Nianyi Wang
  • 712
  • 6
  • 13