Search code examples
javascriptweb-component

How can I get StyleSheet css rules using webcomponent.js


I'm coding a web component recently, and now try to add webcomponentsjs polyfills for other unsupported browser, but I have a problem when I'm using it.

I have to get a childNodes stylesheet css rules for dynamic changes, the code here works fine in chrome:

        node = this['root'].childNodes;
        //this['root']: is <template> element
        //Here is webcomponentjs console.log in Firefox:
        //Object
        // { __impl4cf1e782hg__: <template#sd>,
        //          parentNode_: undefined, firstChild_: undefined, 
        //          lastChild_: undefined, nextSibling_: undefined, 
        //          previousSibling_: undefined, treeScope_: Object }

        style = node[1]['sheet'].cssRules;

        if(bgColor || hairColor){
            for(i = 0; i < style.length; i++){
                if(style[i].selectorText === '.base'){
                    style[i].style.background = bgColor;
                }
                if(style[i].selectorText === '.hair'
                   || style[i].selectorText === '.hair::before'
                   || style[i].selectorText === '.hair::after' ){
                    style[i].style.background = hairColor;
                }
           }
        }

The problem is I can't access node[1]['sheet'].cssRules in webcomponentsjs in firefox and safari, since it's inside one more layer Object { __impl4cf1e782hg__: <template> ... } , although I get inside to it ['__impl4cf1e782hg__'] , but I'm not allow to get anything. How to change this code for webcomponentsjs?

Question is, how can I get cssRules?

I can't see any information about getting sheet in their website. Have any ideas?

Thank you.


Solution

  • The method is different whether you use Shadow DOM or not.

    A way for accessing the sheet inside the polyfilled Shadow DOM is to use the setTimeout() function in the attachedCallback() method, because it's only after that moment that the stylesheet becomes available.

    prototype.attachedCallback = function ()
    {
        var style = this.shadowRoot.querySelector( 'style' )
    
        setTimeout( function () 
        { 
            var sheet = style.sheet
            console.info( 'sheet is ok =>', sheet )
            //you can modify styles here:
            sheet.cssRules[0].style.color = 'dodgerblue'
        } )
    }