An attribute is a named value on an HTML tag. An image’s `src` points to an image; attributes on a custom element can likewise tell a Web Component how to behave. Unlike a JavaScript property, an attribute is visible in the markup. The two can represent the same option, but they do not stay synchronized automatically. section 1.3
Start with values in the tag
A photo carousel can take `title`, `author`, and `photos` attributes. Inside `connectedCallback()`, `getAttribute('title')` supplies its heading, while `getAttribute('photos').split(',')` supplies image paths. A simpler slider can read a color and a `value` attribute to set its background and thumb position. In each case, the tag provides configuration; component code decides what that configuration does. section 2.6 section 2.5
Why put configuration in markup rather than set properties afterward? Values on the tag are available when the element is created. A search component can read its API key and search term with `getAttribute()` and start its initial search in `connectedCallback()`. It can still check that both values exist. This avoids separate JavaScript assignments, though it does not yet handle a search term changed later. section 3.3 section 3.2
Choose how each attribute should behave:
- For an optional, initial-only option, check `hasAttribute()` before reading it. A search component uses this for thumbnail height and background color, retaining fallback sizes or CSS styling when either is absent. section 3.5
- For a value that can change, include its name in `observedAttributes` and respond in `attributeChangedCallback()`. A `layout` attribute can select an HTML template; a menu changes it with `setAttribute()`. Its initial value also triggers the callback. section 7.3
- If both markup and a JavaScript property should offer the same option, consider reflection: have the property read or set the attribute, then respond to the attribute change. Avoid having each change handler set the other side again; that can cause an infinite loop. section 3.5 section 1.3
Listing 3.20. Adding a getter/setter in addition to existing attributes for reflection
static get observedAttributes() {
return ['searchterm'];
}
get searchTerm() {
return this.getAttribute('searchTerm'); #1
}
set searchTerm(val) {
this.setAttribute('searchTerm', val); #2
}
attributeChangedCallback(name, oldval, newval) {
if (name === 'searchterm') {
this.doSearch(); #3
}
}
The search-term listing shows a getter reading an attribute, a setter writing it, and an attribute-change callback starting a search. section 3.5
Attributes and properties are options, not competing rules for every value. The familiar `<input>` illustrates why the distinction matters: its `value` attribute retains the initial value even after the JavaScript `value` property changes. Decide deliberately whether a custom element should behave that way or keep its two interfaces in sync. section 1.3 section 3.7

























