Testing the <slot> element

The Web Component <slot> element is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together.

Example 1

In this example, a <my-component> web component is added to the page, and it can be treated like a separate document, with it's own styles. The slots are defined in JavaSCript.

Hello, World!

This is a paragraph inside the custom component.

HTML markup:

<my-component>
  <h1 slot="title">Hello, World!</h1>
  <p slot="content">This is a paragraph...</p>
</my-component>

JavaScript:

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

        const shadow = this.attachShadow({ mode: 'open' });

        shadow.innerHTML = `
            <style>
                .container {
                    border: 2px solid #000;
                    padding: 10px;
                    border-radius: 5px;
                    width: 300px;
                }
                ::slotted(h1) {
                    color: blue;
                }
                ::slotted(p) {
                    color: green;
                }
            </style>
            <div class="container">
                <slot name="title"></slot>
                <slot name="content"></slot>
            </div>
        `;
    }
}