Observed Attributes
Declaring watched attributes
Section titled “Declaring watched attributes”The browser only tracks attributes you explicitly opt in to. The static getter observedAttributes must return an array of attribute name strings:
static get observedAttributes() { return ['color', 'label'];}Only attributes that appear in this array will ever trigger attributeChangedCallback. If the array is empty — or the getter is missing entirely — attribute changes are silently ignored.
The attributeChangedCallback signature
Section titled “The attributeChangedCallback signature”When a watched attribute is added, changed, or removed, the browser calls:
attributeChangedCallback(name, oldValue, newValue) { // name — the attribute name, e.g. 'color' // oldValue — the previous value string, or null on first set // newValue — the new value string, or null when removed}All three parameters are strings (or null). On the very first time an attribute is set, oldValue is null. When an attribute is removed with removeAttribute, newValue is null.
Full pattern
Section titled “Full pattern”class AttrColor extends HTMLElement { static get observedAttributes() { return ['color', 'label']; }
connectedCallback() { this._render(); }
attributeChangedCallback(name, oldValue, newValue) { this._render(); }
_render() { var color = this.getAttribute('color') || '#6366f1'; var label = this.getAttribute('label') || '?'; this.innerHTML = '<span style="' + 'display:inline-block;' + 'padding:.25rem .75rem;' + 'border-radius:9999px;' + 'background:' + color + ';' + 'color:#fff;' + 'font-weight:600;' + 'font-family:sans-serif;' + 'font-size:.875rem' + '">' + label + '</span>'; }}
customElements.define('attr-color', AttrColor);Live demo
Section titled “Live demo”Try editing color="#4f46e5" to another CSS color value, or change the label text in the HTML panel — the badges re-render immediately.