textContent empty in connectedCallback() of a custom HTMLElement

后端 未结 3 1471
说谎
说谎 2021-01-14 04:24

Within the connectedCallback() method of my custom element the textContent is returned as an empty string.

Essentially my code boils down t

3条回答
  •  长情又很酷
    2021-01-14 04:54

    You can access the content using a slot and the slotchange event (the slot gets the host tag content.)

    (function(){
        
        class MyComponent extends HTMLElement {
            
            constructor() {
                super();
                
                let slot = document.createElement('slot') ;
    
                slot.addEventListener('slotchange', function(e) {
                    let nodes = slot.assignedNodes();
                    console.log('host text: ',nodes[0].nodeValue);                               
                });
      
                const shadowRoot = this.attachShadow({mode: 'open'});
                shadowRoot.appendChild(slot);     
            }
            
        }
                
        window.customElements.define('my-component', MyComponent);
    })();
    This is the content I need to access

提交回复
热议问题