Skip to content
","url":"https://ez4code.com/snippets/html-web-components","keywords":"web-components, component","author":{"@type":"Person","name":"EZ4Code Team"},"publisher":{"@type":"Organization","name":"EZ4Code","logo":{"@type":"ImageObject","url":"https://ez4code.com/logo.png"}},"datePublished":"2024-01-01","dateModified":"2026-08-01","image":"https://ez4code.com/og-image.png"}
HTML

Web Components

Custom elements and Shadow DOM.

By EZ4Code Team
web-componentscomponent

Code

<!-- Using custom elements -->
<my-button color="blue" size="large">
    Click Me
</my-button>

<script>
class MyButton extends HTMLElement {
    constructor() {
        super();
        const shadow = this.attachShadow({ mode: 'open' });

        const style = document.createElement('style');
        style.textContent = `
            :host { display: inline-block; }
            button {
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
                background: var(--color, #3498db);
                color: white;
            }
            button:hover { opacity: 0.9; }
            button.large { padding: 12px 24px; font-size: 16px; }
        `;

        const btn = document.createElement('button');
        btn.textContent = this.textContent || 'Button';

        const color = this.getAttribute('color');
        if (color) btn.style.setProperty('--color', color);

        const size = this.getAttribute('size');
        if (size) btn.classList.add(size);

        btn.addEventListener('click', () => {
            this.dispatchEvent(new CustomEvent('my-click', {
                detail: { message: 'clicked' }
            }));
        });

        shadow.appendChild(style);
        shadow.appendChild(btn);
    }

    // Observe attribute changes
    static get observedAttributes() {
        return ['color', 'size'];
    }

    attributeChangedCallback(name, oldVal, newVal) {
        // Update button style
    }
}

customElements.define('my-button', MyButton);

// Listen for custom events
document.querySelector('my-button')
    .addEventListener('my-click', (e) => {
        console.log(e.detail.message);
    });
</script>

Explanation

Web Components define custom elements via customElements; Shadow DOM isolates styles; slot projects content.

More HTML Snippets