Search code examples
stylesheetweb-componentcustom-element

Extending HTMLStyleElement with Custom Elements v1


For years I have managed my (many) STYLE elements with the pattern:

[simplified code for brievity]

    <STYLE id="theme1" onload="myStyleManager.init(this)">
       ...
    </STYLE>
    <STYLE id="theme2" onload="myStyleManager.init(this)">
       ...
    </STYLE>
    <STYLE id="devmode" onload="myStyleManager.init(this)">
       ...
    </STYLE>

In myStyleManager I can then easy

  • disable/enable STYLE definitions
  • add/delete rules
  • etc

Custom Elements Objective:

Replace <STYLE> with <CARDTS-STYLE> so I can init in the connectedCallback:

    class StyleElement extends HTMLStyleElement {
        constructor() {
            super();
        }
        connectedCallback() {
            myStyleManager.init(this);
        }
    }
    __defineElement('cardts-style', StyleElement);

This (ofcourse) doesn't work because I can only extend HTMLElement

0 results searching StackOverflow for [custom element] HTMLStyleElement

And the rest of the Web doesn't have any pointer either.

Questions:

  1. Is it possible to extend STYLE?
  2. Is it better to wrap CARDTS-STYLE around a child element STYLE?

Solution

  • Is it possible to extend STYLE?

    Yes

    Is it better to wrap CARDTS-STYLE around a child element STYLE?

    I don't think so but it depends on what you want to achieve.


    If you want to manage stylesheet you may consider using a new feature called Constructable Stylesheets that will permit to load, define and add CSS stylesheets to HTML document and to Shadow DOMs as well.

    You can find a running illustration in this post that already works with Chrome 73 and Opera 60.