Search code examples
javascripthtmlweb-componentcustom-element

How can I add child elements to a custom element in HTML markup?


I want to create a custom element that's able to host any HTML markup within:

<my-custom-element>
  <p>This is some message.</p>
  <div><button>Click here</button></div>
</my-custom-element>

The above markup doesn't seem to work. Every browser renders it like:

<my-custom-element></my-custom-element>
  <p>This is some message.</p>
  <div><button>Click here</button></div>

How can I have a custom element contain child elements in markup?


Solution

  • If you are using shadowDOM then you need to add a <slot> into your shadowDOM.

    class MyElement extends HTMLElement {
      constructor() {
        super();
        this.attachShadow({mode: 'open'}).innerHTML = '<style>:host{border:1px dashed red;display:inline-block;}</style><slot></slot>';
      }
    }
    
    customElements.define('my-element', MyElement);
    <my-element>
      <p>This is some message.</p>
      <div><button>Click here</button></div>
    </my-element>