Search code examples
javascripthtmlcssstylesheet

What is the difference between HTMLStyleElement and CSSStyleElement


I'm been digging a little in Style Sheets, I was trying to access a <style> tag the same way I could access a styleSheet element, for example.

<style id="myStyle">
</style>

var myStyle = document.getElementById("myStyle");
alert(myStyle.cssRules[0]);

But this didn't work, then I decided to check the type of the <style> tag.

alert(myStyle);

And it gave me this :

[object HTMLStyleElement]

So I checked the type of a styleSheet.

alert(document.styleSheets[0]);

And it gave me this:

[object CSSStyleElement]

So what is the real difference? And how can I access the rules in <style> tag other than using .innerHTML? And how can I create a new styleSheet?


Solution

  • There's a big difference actually.

    HTMLStyleElement is actually a flavor of HTMLElement - a wrapper containing some DOM structure. What's great about it is that it implements LinkStyle interface as well, therefore giving us ability to access its underlying stylesheet (via sheet property).

    CSSStyleSheet, on the contrary, is not related to DOM - it's a specific wrapper for CSS style sheets (containing CSS rules). It lets you manipulate CSS styling via deleteRule and insertRule methods, or by changing an existing rule (via style property).

    Answering your specific question, check the following:

    HTML:

    <style id="myStyle">
        p { background-color: lime; }
    </style>
    

    JS:

    var myStyle = document.getElementById("myStyle");
    alert(myStyle.sheet.cssRules[0].cssText);
    

    As you see, here we first access CSSStyleSheet wrapped by #myStyle element, then access its specific rule (CSSRule), then - its text.

    P.S. I wrote a small demo illustrating how one can manipulate stylesheets dynamically. It's not pretty, and by a reason: changing presentation by swapping classes is far better technique. Still, it can be done even this way. )