2

I need to extract certain rules of an external CSS style sheet file. I can execute a http-get to get the content of the style sheet.

Then I try to load that content into a HTMLStyleElement to later enumerate the rules an pick the ones I'm interested into.

However, the HTMLStyleElement.sheet property is always null after I created the element and that's why I cannot enumerate through the rules.

My code looks like this:

let css: HTMLStyleElement = document.createElement("style");

    // the sample code below will be loaded from an external source, but for this example I hardcoded something ...
    let cssTxt = 'div {border: 2px solid black; background-color: blue;} @font-face { font-family: Roboto; font-style: normal; font-weight: 700; src: url(roboto-v18-latin_latin-ext-700.53950ed05f8532ac.eot); src: local("Roboto Bold"),local("Roboto-Bold"),url(roboto-v18-latin_latin-ext-700.53950ed05f8532ac.eot?#iefix) format("embedded-opentype"),url(roboto-v18-latin_latin-ext-700.9d541330b4ce7057.woff2) format("woff2"),url(roboto-v18-latin_latin-ext-700.c52f983fe85258f7.woff) format("woff"),url(roboto-v18-latin_latin-ext-700.8d9b6be89e992a10.ttf) format("truetype"),url(roboto-v18-latin_latin-ext-700.4cf5420d5ce6b793.svg#Roboto) format("svg")}';
    
    css.innerHTML = cssTxt; // the same applies when I try to innerText ...
    
    for (const rule of css.sheet.cssRules) { // <-- here we face the problem, css.sheet is always null
        if (rule.constructor.name == "certainName") {
            // I'm interested into this rule
            console.log(rule.cssText);
        }
    }

What I'm doing wrong and how can I make the code run so I'm able to enumerate the rules ...

[EDIT 2023-11-15] The 'duplicate' (how to get a CSSStyleSheet object from a HTMLStyleElement element) question does not reflect the question in this post. While the marked duplicate want's to create a new CSS style element, I want extract styles from a previous created css style element. The questions are about the same topic, but they differ in the goal, the posted solution there cannot help to solve the issue in this post here: The problem with the null property still remains.

2
  • 2
    It may be that you'll have to attach the element to the DOM first. Commented Nov 14, 2023 at 13:21
  • Maybe useful Commented Nov 14, 2023 at 13:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.