An attribute is a named value written on an HTML element, such as `<hello-world name="Alpha"></hello-world>`. It lets you supply data to a web component directly in markup. JavaScript can read or change the value with `getAttribute` and `setAttribute`. An attribute’s value is always a string. section 3.3 section 4.2.10
A greeting that follows its attribute
A `hello-world` component can read its `name` attribute and display “Hello, Alpha!” Changing the attribute to `Beta` changes the greeting when the component observes `name` and renders again. Without a name, it can display “Hello, World!” section 3.3
Listing 3.7 The source of truth is the name attribute
class HelloWorld extends HTMLElement {
static get observedAttributes() {
return ["name"];
}
attributeChangedCallback(_name, _oldValue, _newValue) {
this.render();
}
connectedCallback() {
this.render();
}
get name() {
return this.getAttribute("name");
}
set name(value) {
this.setAttribute("name", value);
}
render() {
const name = this.getAttribute("name") || "World";
const p = document.createElement("p");
p.textContent = `Hello, ${name}!`;
this.replaceChildren(p);
}
}
customElements.define("hello-world", HelloWorld);
The implementation observes `name`, renders when it changes, and exposes a `name` property whose getter and setter delegate to the attribute. section 3.3
Choose attributes and properties according to the data:
- For strings, numbers, and Booleans, allow both an attribute and a property where practical. Encode numbers as strings; represent a Boolean with the presence or absence of a valueless attribute. Keep corresponding values in sync, and guard setters against repeated updates. section 4.2.8
- For objects and arrays, use properties instead. Encoding them into attribute strings costs time and memory, and JSON cannot preserve references to other objects. Do not reflect rich-data properties back to attributes. section 4.2.10 section 4.2.11
A component can designate either its attribute or its property as the source of truth and make the other delegate to it. This permits configuration in HTML and convenient access in JavaScript. It also matters when a framework assigns an attribute value to a same-named property and removes the attribute: a component that keeps the two routes consistent can still respond as intended. section 3.3































