A custom element can read an attribute when it first renders, but that alone will not update its UI if the attribute changes later. For `<hello-world name="Mark"></hello-world>`, observing `name` and implementing `attributeChangedCallback` lets the greeting respond to a later `setAttribute("name", "Ada")`. section 3.1.2
Listing 3.2 hello-world.js
class HelloWorld extends HTMLElement {
static get observedAttributes() { #1
return ["name"];
}
attributeChangedCallback(_name, _oldValue, _newValue) { #2
this.render();
}
connectedCallback() {
this.render();
}
render() { #3
const name = this.getAttribute("name") || "World";
const p = document.createElement("p");
p.textContent = `Hello, ${name}!`;
this.replaceChildren(p);
}
}
customElements.define("hello-world", HelloWorld);
The greeting component lists `name` in `observedAttributes`. Both `attributeChangedCallback` and `connectedCallback` call the same `render` method, so initial display and later changes use one rendering path. section 3.1.2
Define `attributeChangedCallback(attrName, oldValue, newValue)` on an `HTMLElement` subclass, and list the attributes to watch in its static `observedAttributes`. The browser calls the callback when an observed attribute changes, including when its initial value is assigned. Use `attrName` to choose an action when several attributes are observed; parameters you do not need can be left unused. section 3.1.2 section 3.2
Choose the update that fits the component:
- For a small component, call a shared `render` method after an observed attribute changes. section 3.1.2
- For several attributes, copy the changed value into its corresponding property. A radio group rerenders after relevant changes only once connected; changing `value` instead uses its setter to update the selected button. section 3.10
- When a property setter also calls `setAttribute`, check whether the value actually changed to avoid an update loop. section 4.2.8 section 9.1
Do not assume the element is connected when the callback runs: setting an attribute before appending a new element can invoke `attributeChangedCallback` before `connectedCallback`. If an update requires an existing DOM, defer that work until connection or guard it with a connected-state check. Attribute values are strings; interpret them as needed, or use `hasAttribute()` for presence-based Boolean attributes. section 3.1.2 section 3.10

