typestar

Shadow DOM and slots in HTML

The component owns its markup; the page owns the content that goes in it.

<info-card>
  <h3 slot="title">Ownership</h3>
  <p>Each value has one owner at a time.</p>
</info-card>
<template id="card-template">
  <article class="card">
    <slot name="title"></slot>
    <div class="body"><slot></slot></div>
  </article>
</template>

<script>
  customElements.define('info-card', class extends HTMLElement {
    connectedCallback() {
      const template = document.getElementById('card-template');
      this.attachShadow({ mode: 'open' })
        .append(template.content.cloneNode(true));
    }
  });
</script>

How it works

  1. A shadow root hides the internals from the page's CSS and queries.
  2. <slot> is the hole the page's own children drop into.
  3. A named slot takes the elements whose slot attribute matches.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
489
Tokens
131
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 98 seconds.

Type this snippet

Step 3 of 3 in Templates & components, step 7 of 13 in Interactive HTML.

← Previous Next →