Blog>
Snippets

Nested Named Slots

Demonstrates the creation of a component with nested named slots and how to access the slots at different nesting levels.
<template id="my-component">
  <style>
    .container {
      border: 2px solid #333;
      padding: 16px;
    }
    .header, .footer {
      background-color: #eee;
    }
  </style>
  <div class="container">
    <div class="header">
      <slot name="header"></slot>
    </div>
    <div class="content">
      <slot></slot>
    </div>
    <div class="nested-slot">
      <slot name="nested"></slot>
    </div>
    <div class="footer">
      <slot name="footer"></slot>
    </div>
  </div>
</template>
This is the template for a web component with named slots for 'header', 'nested', and 'footer'. It also includes a default slot for the main content.
class MyComponent extends HTMLElement {
  constructor() {
    super();
    const shadowRoot = this.attachShadow({ mode: 'open' });
    const template = document.getElementById('my-component').content;
    shadowRoot.appendChild(template.cloneNode(true));
  }
}

customElements.define('my-component', MyComponent);
This is the JavaScript part that defines a custom element 'my-component' and attaches the shadow DOM to use the template defined earlier.
<my-component>
  <div slot="header">This is the header content.</div>
  <div>This is the default content.</div>
  <div slot="nested">
    <my-sub-component>
      <div slot="sub-content">This is nested content inside the 'nested' slot.</div>
    </my-sub-component>
  </div>
  <div slot="footer">This is the footer content.</div>
</my-component>
This is the HTML usage of the 'my-component' with content inserted into the named slots and the default slot, including another custom component with its own slot nested inside.
<template id="my-sub-component">
  <style>
    .nested-container {
      background-color: #f0f0f0;
      padding: 8px;
      margin-top: 8px;
    }
  </style>
  <div class="nested-container">
    <slot name="sub-content"></slot>
  </div>
</template>
This is the template for a sub-component 'my-sub-component' with its own slot named 'sub-content', which will be nested within the 'nested' slot of 'my-component'.
class MySubComponent extends HTMLElement {
  constructor() {
    super();
    const shadowRoot = this.attachShadow({ mode: 'open' });
    const template = document.getElementById('my-sub-component').content;
    shadowRoot.appendChild(template.cloneNode(true));
  }
}

customElements.define('my-sub-component', MySubComponent);
This is the JavaScript that defines the 'my-sub-component' custom element to be used within the 'my-component' parent's 'nested' slot.