← Trilha· Lição 2 de 8
Custom Element + Shadow DOM
class extends HTMLElement, define(), attachShadow e estilos encapsulados.
Um Custom Element é uma classe que estende HTMLElement e é registrada com um nome que contenha hífen.
Anatomia mínima
class HelloBadge extends HTMLElement {
connectedCallback() {
this.textContent = this.getAttribute('label') || 'Olá';
}
}
customElements.define('hello-badge', HelloBadge);
<hello-badge label="CSS4HTML"></hello-badge>
Shadow DOM
Sem shadow, o CSS da página vaza para dentro (e o CSS do componente vaza para fora). Com shadow:
connectedCallback() {
const root = this.attachShadow({ mode: 'open' });
root.innerHTML = `
<style>
span { color: #F5A623; font-weight: 700; }
</style>
<span><slot></slot></span>
`;
}
mode: 'open'—element.shadowRootfica acessível (útil para debug e testes)<slot>— projeta filhos do light DOM para dentro do shadow
Atributos observados
static get observedAttributes() { return ['label']; }
attributeChangedCallback(name, _old, value) {
// atualizar UI
}
Pratique nos exemplos Hello element e Shadow styles.