Safari NotSupportedError Custom Element in shadowRoot.innerHTML in constructor of parent Custom Element

791 views Asked by At

I'm creating a custom element and setting its shadowRoot to include other custom elements, which throws NotSupportedError (DOM Exception 9): A newly constructed custom element must not have child nodes. (Note that it doesn't throw the error when there is no child custom-element in the markup.)

Is there an appropriate way to change my constructor so that I don't throw this NotSupportedError in Safari?

Is there a better way to setup this elements and its content?

Why is this happening only when I have another custom element within its markup?

Thanks. The following is an excerpt of the relevant work.

class MyControl extends HTMLElement{
constructor(){
    super();

    var shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = `<slot name=form><select-provider src="/path/to/endpoint"></select-provider></slot>
`;
}
}
customElements.define('my-control', MyControl);
class SelectProvider extends HTMLElement{
constructor(){
    super();

    var shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = `<slot></slot>
`;
}
/* omitted handling of src, loading url */
render(){/* rewrite select with options */}
}
customElements.define('select-provider', SelectProvider);
</script>
<my-control><span>this custom element throws and error in Safari</span></my-control>
1

There are 1 answers

3
jimmont On

My child select-provider was doing a this.appendChild in the constructor which throws this error. Otherwise it works as expected. To resolve I simply moved this into the connectedCallback.