Using ShadowRoot to create light reusable JS components

Costas

Administrator
Staff member
JavaScript:
<html lang="en">
<body>
    <text-input>
        <label>Search:</label>
    </text-input>
 
    <script>
        class TextInput extends HTMLElement {
            constructor() {
                super();
                const shadow = this.attachShadow({ mode: 'open' });

                shadow.innerHTML = `
                    <slot></slot>
                    <input id="search" type="text">
                `;
            }
        }
     
        customElements.define('text-input', TextInput);

        const slottedLabel = document.querySelector('text-input label');
        const internalInput = document.querySelector('text-input').shadowRoot.querySelector('input');

        console.log('slot:', slottedLabel);
        console.log('input:', internalInput);
        slottedLabel.style.color = 'blue';
    </script>
</body>
</html>

source :

internal ref
 
Top