Attributes and properties
Attributes are text and properties hold any value. Learn web component attributes vs properties, how to reflect one into the other, and which to reflect.
- 01Tell the two apart as an authorSay what an attribute can do that a property can't, and the other way round: types, CSS, DevTools, and HTML.
- 02Reflect a property without a loopWrite a getter that reads the attribute and a setter that writes it, or a private field with a guard.
- 03Choose what to reflect, and convert itReflect short settings and styling hooks, keep objects and fast-changing values as properties, and turn text into numbers and dates.
Should a web component use attributes or properties?
Asha is building the menu page for Leaf and Kettle. Each tea has a label from the tea kit, like <tea-label name="Green tea" minutes="4">. Today, green tea brews for 5 minutes. So her script runs label.minutes = 5. No error shows. But the label still says 4 minutes.
She asks Ravi, who writes the kit, to fix it. Ravi has three questions. Should the label have a minutes property? Should setting it change the attribute too? And should it give back the text "5" or the number 5?
An attribute is text written in the HTML. A property is a value on the element object in JavaScript, and it can be any type. For each simple setting, give your component both. Then make the property reflect the attribute. Its getter, the function that runs when code reads the property, reads the attribute. Its setter, the function that runs when code sets it, writes the attribute.
Here is Asha's page. It loads the kit as lesson 4.3 left it. That kit's label only reads attributes:
<p><tea-label name="Green tea" minutes="4"></tea-label></p> <script type="module"> await import("./tea-kit/index.js"); const label = document.querySelector("tea-label"); label.minutes = 5; console.log(label.textContent); console.log(label.getAttribute("minutes"), label.minutes);</script>- Line 1 writes the label with two attributes,
nameandminutes. - Line 4 loads the kit. Line 5 finds the label.
- Line 6 sets
label.minutesto 5. - Line 7 prints
Green tea: brew for 4 minutes. The text didn't change. - Line 8 prints
4 5. The attribute says 4, and the property says 5.
So the label now has two minutes. One is the attribute, text in the HTML. The other is a property, a number on the JavaScript object. The kit's class only reads the attribute. Nothing reads the property. So line 6 changed nothing you can see.
4. Line 6 put 5 in a property on the object, and nothing in the class reads it.At Leaf and Kettle, each tin of tea has a paper tag on the shelf. Anyone walking past can read it. The till keeps its own record of each price, as a number it can add up. If Ravi changes the till but not the tag, the two disagree. A good shop keeps them in step.
- In real life: The paper tag on the shelf
- In JavaScript: The attribute
minutes="4": text anyone can read in the HTML - In real life: The till's record
- In JavaScript: The property
label.minutes: a value JavaScript works with - In real life: Changing the till but not the tag
- In JavaScript:
label.minutes = 5on a label with no such property - In real life: Keeping the tag and the till in step
- In JavaScript: Reflecting the property to the attribute
Attributes are text in the HTML. Properties are values on the object, of any type. A custom element links the two only if its class does. For simple settings, make the property reflect the attribute, so both always say the same thing.
Lesson 2.2 looked at attributes and properties from the outside, as someone using a component. This lesson is the other side. You write the class, so you decide which settings get an attribute, which get a property, and how the two stay in step. For getAttribute() and setAttribute() themselves, see Attributes & properties in the JavaScript path.
Why are attributes always strings?
HTML is text. Every attribute in it is a name and a piece of text. So when JavaScript writes an attribute, the browser turns the value into text first. Try it:
<style> tea-label[minutes="5"] { font-weight: bold; }</style><p><tea-label name="Green tea" minutes="4"></tea-label></p> <script type="module"> await import("./tea-kit/index.js"); const label = document.querySelector("tea-label"); label.setAttribute("minutes", 5); console.log(typeof label.getAttribute("minutes")); console.log(document.querySelector('[minutes="5"]') === label);</script>- Lines 1 to 3 are a CSS rule. It makes any
tea-labelwithminutes="5"bold. - Line 9 writes the attribute with the number 5.
- Line 10 prints
string. The browser stored the text"5". - Line 11 finds an element by its attribute. It prints
true.
The result shows the label in bold, with the new time. The CSS rule matched as soon as the attribute changed. The label drew itself again too, because it observes minutes, as lesson 3.4 set up.
Attributes are part of the HTML, so many things can see them:
- CSS selectors, like
tea-label[minutes="5"]. querySelector(), as line 11 shows.- The Elements panel in DevTools.
- The element's HTML, like
outerHTML, and the HTML a server sends. attributeChangedCallback(), and anyMutationObserver: the browser's tool for watching an element for changes.
Why it matters: anything a page author writes in HTML, or styles with CSS, has to be an attribute. And every attribute is text. So when your class needs a number, it has to turn the text into one.
What can a property hold that an attribute can't?
A property is a value stored on the element object. It never goes through HTML, so it keeps its type. A number stays a number. An object stays an object. Here a cup takes a whole blend: an object with a tea and a list of extras.
<tea-cup></tea-cup> <script> class TeaCup extends HTMLElement { #blend; get blend() { return this.#blend; } set blend(value) { this.#blend = value; this.textContent = `${value.tea} with ${value.extras.join(" and ")}`; } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); cup.blend = { tea: "Green tea", extras: ["mint", "honey"] }; console.log(cup.blend.extras.length); console.log(cup.getAttribute("blend"));</script>- Line 5 is a private field,
#blend. A name that starts with#can only be used inside the class. - Lines 6 to 8 are a getter: a function that runs when code reads
cup.blend. It gives back the field. - Lines 9 to 12 are a setter: a function that runs when code sets
cup.blend. It keeps the object and writes the cup's text. - Line 17 sets the property to an object.
- Line 18 prints
2. The list of extras arrived whole. - Line 19 prints
null. There is noblendattribute.
The result shows Green tea with mint and honey. An attribute couldn't do that. In lesson 2.2, an object written into an attribute turned into the text [object Object]. The Getters & setters lesson explains get and set in full.
Now the other side. Nothing outside JavaScript can see a property. CSS can't select on it. The Elements panel doesn't list it. And the element's HTML leaves it out:
const cup = document.createElement("tea-cup");
cup.setAttribute("size", "large");
cup.blend = { tea: "Green tea" };
console.log(cup.outerHTML);Line 2 writes an attribute. Line 3 sets a property. Line 4 prints the element's HTML: <tea-cup size="large"></tea-cup>. The size is there. The blend isn't.
Why it matters: properties are how you hand a component lists, objects, and functions. Attributes are how people set it up from HTML. In Jake Archibald's words, attributes are for configuration, and properties can hold state.
How do built-in elements reflect attributes?
Before you write your own, look at how the browser's elements do it. Most of their attributes come with a property of the same name. Set one, and the other changes too:
const div = document.createElement("div");
div.id = "menu";
div.hidden = true;
console.log(div.outerHTML);
div.setAttribute("id", "specials");
console.log(div.id);- Lines 2 and 3 set two properties,
idandhidden. - Line 4 prints
<div id="menu" hidden=""></div>. Both became attributes. - Line 5 changes the attribute. Line 6 prints
specials. The property followed.
The HTML Standard has a word for this link: reflect. In its words, the getter "returns the current value of the content attribute, and the setter changes the value of the content attribute". A content attribute is the standard's name for an attribute in the HTML. The property is called an IDL attribute. So a reflecting property keeps no value of its own. It's a way to read and write the attribute.
The standard marks which properties reflect. Below is part of a text box's interface, the list of properties every <input> has. Read [Reflect] as "this property reflects the attribute with the same name". [Reflect="checked"] names a different attribute. A line with no [Reflect] keeps its own value.
interface HTMLInputElement : HTMLElement {
[Reflect] attribute boolean disabled;
[Reflect="checked"] attribute boolean defaultChecked;
attribute boolean checked;
[Reflect="value"] attribute DOMString defaultValue;
attribute DOMString value;
};In plain words, line by line:
- Line 1 starts the interface for every text box, checkbox, and other input.
- Line 2:
disabledreflects thedisabledattribute. - Line 3:
defaultCheckedreflects thecheckedattribute. - Line 4:
checkedreflects nothing. It says whether the box is ticked now. - Line 5:
defaultValuereflects thevalueattribute. - Line 6:
valuereflects nothing. It's the text in the box now.
So the value attribute isn't the live value. The standard says it "gives the default value" of the input. Type into this box, and press Read:
<form> <input value="Green tea"> <button type="button">Read</button> <button type="reset">Reset</button></form> <script> const input = document.querySelector("input"); document.querySelector("button").addEventListener("click", () => { console.log("value:", input.value); console.log("attribute:", input.getAttribute("value")); console.log("defaultValue:", input.defaultValue); });</script>- Line 2 is a text box. Its
valueattribute isGreen tea. - Line 4 is a Reset button. It puts the form back to its defaults.
- Lines 10 to 12 print the property, the attribute, and
defaultValue.
Before you type, Read prints Green tea three times. Now type Mint tea and press Read. It prints value: Mint tea, attribute: Green tea, and defaultValue: Green tea. The attribute kept the default. Press Reset, then Read. The value is back to Green tea.
value property. The value attribute keeps the default, and defaultValue is the property that reflects it.Ravi has a regular customer. Her card behind the counter says "Usual: green tea". Today she asks for mint tea, and Ravi makes mint. The card still says green tea. Tomorrow she just says "the usual", and Ravi reads the card again.
- In real life: The card that says "Usual: green tea"
- In JavaScript: The
valueattribute, read bydefaultValue - In real life: What she asks for today
- In JavaScript: The
valueproperty: what's in the box now - In real life: Saying "the usual" tomorrow
- In JavaScript: Resetting the form, which goes back to the default
A checkbox works the same way. checked is whether it's ticked now, and defaultChecked reflects the checked attribute. The JavaScript path covers both in text boxes, checkboxes, and starting values.
Why it matters: your own components choose between these two patterns too. Most settings reflect, like id. A value the user changes, like what they type, can live in a property, with the attribute as its default.
How do you reflect a property to an attribute?
A custom element gets none of this for free. The label from the overview had a minutes attribute and no property at all. To link the two, your class writes a getter and a setter. Chrome's custom elements guidance shows two designs. The first keeps the attribute as the only place the value lives:
<p><tea-label minutes="4"></tea-label></p> <script> class TeaLabel extends HTMLElement { static observedAttributes = ["minutes"]; get minutes() { return Number(this.getAttribute("minutes")); } set minutes(value) { this.setAttribute("minutes", value); } attributeChangedCallback() { this.textContent = `Brew for ${this.minutes} minutes`; } } customElements.define("tea-label", TeaLabel); const label = document.querySelector("tea-label"); label.minutes = 5; console.log(label.minutes, typeof label.minutes); console.log(label.getAttribute("minutes"));</script>- Line 5 observes
minutes, so the class hears about changes. - Lines 7 to 9 are the getter. It reads the attribute and turns the text into a number with
Number(). - Lines 11 to 13 are the setter. It writes the attribute, and that's all.
- Lines 15 to 17 are the callback. It draws the label, using the getter.
- Line 22 sets the property. Line 23 prints
5 number. Line 24 prints5, the attribute.
Follow line 22. The setter writes the attribute. Writing the attribute runs the callback. The callback reads the getter and draws Brew for 5 minutes. Then it stops, because nothing calls the setter again.
This design has one rule: the callback only draws. In lesson 3.4, the callback set the property, and the setter wrote the attribute. The two called each other until Chrome threw a RangeError. Here, nothing calls back. web.dev's checklist shows this shape, under Avoid reentrancy issues.
Leaf and Kettle keeps today's brewing times on one whiteboard in the kitchen. Anyone who needs a time reads the board. Anyone who changes a time writes on the board. Nobody keeps a second list in a pocket. So there's never an old time to argue about.
- In real life: The whiteboard
- In JavaScript: The
minutesattribute: the one place the value lives - In real life: Reading the board
- In JavaScript: The getter, with
getAttribute() - In real life: Writing on the board
- In JavaScript: The setter, with
setAttribute() - In real life: The cook who redraws the menu when the board changes
- In JavaScript:
attributeChangedCallback(), which only draws
Now compare three versions of the class. The page has two buttons. One sets the property, and one sets the attribute. Press both, in any order:
<p><tea-label minutes="4"></tea-label></p><button id="property">Set the property to 5</button><button id="attribute">Set the attribute to 6</button><p id="readout"></p> <script src="tea-label.js"></script><script> const label = document.querySelector("tea-label"); const readout = document.querySelector("#readout"); function show() { readout.textContent = `Property: ${label.minutes}. Attribute: ${label.getAttribute("minutes")}.`; } document.querySelector("#property").onclick = () => { label.minutes = 5; show(); }; document.querySelector("#attribute").onclick = () => { label.setAttribute("minutes", "6"); show(); }; show();</script>The setter keeps 5 in a private field and never writes the attribute, so the attribute stays 4. Setting the attribute to 6 then redraws the label, but the property still says 5. Two places, two answers.
With A property that doesn't reflect, the two drift apart. After both buttons, the label says 6, the property says 5, and the attribute says 6. Which one is right? Nobody can tell. With The attribute is the source, the readout always shows one value twice.
A private field as the source
The second design keeps the value in a private field. The setter copies it out to the attribute. It's the playground's third version:
class TeaLabel extends HTMLElement {
static observedAttributes = ["minutes"];
#minutes = 0;
get minutes() {
return this.#minutes;
}
set minutes(value) {
this.#minutes = Number(value);
this.setAttribute("minutes", this.#minutes);
this.textContent = `Brew for ${this.#minutes} minutes`;
}
attributeChangedCallback(name, oldValue, newValue) {
if (Number(newValue) === this.#minutes) return;
this.minutes = newValue;
}
}
customElements.define("tea-label", TeaLabel);- Line 3 is the field. It holds the number.
- Line 6: the getter gives back the field. There's no text to convert.
- Lines 10 and 11: the setter keeps the number, then writes it out to the attribute.
- Line 16 is the guard. If the attribute already matches the field, the callback stops.
- Line 17 copies a new attribute value into the field, through the setter.
Here the callback does call the setter, so it needs the guard. When the setter writes the attribute, the callback runs. It sees the same number, and stops at line 16. Take line 16 out, and the page throws the RangeError from lesson 3.4.
So which design should you pick? Chrome's guidance calls the attribute "the right default for a handful of simple, string-ish attributes". Its reason: "there is only one place the state can live, so it can't desync". Pick a field when your code reads the value very often. Reading a field is cheaper than turning text into a value every time. Read each row across:
| What you want to know | The attribute is the source | A field is the source |
|---|---|---|
| Where does the value live? | Only in the attribute. | In a private field, with a copy in the attribute. |
| What does the getter do? | It reads the attribute and converts the text, every time. | It gives back the field. There's no text to convert. |
| Can the two disagree? | No. There is only one value. | Only if the setter forgets to write the attribute. |
| Does the callback need a guard? | No. It only draws, and never calls the setter. | Yes. It calls the setter, and the setter writes the attribute again. |
| When does it fit? | A few short settings, like name and minutes. | Values your code reads very often, or keeps as numbers and objects. |
Lit, the library in stage 8, can do this for you. A property declared with reflect: true writes its attribute after each change. Its docs say Lit keeps track of its own writes, so this can't loop.
Which properties should reflect to attributes?
Not every property should reflect. Each reflected change writes an attribute, and that isn't free. This page reflects a timer's seconds left, 60 times, and counts what happens:
<tea-timer></tea-timer> <script> class TeaTimer extends HTMLElement { static observedAttributes = ["left"]; calls = 0; set left(value) { this.setAttribute("left", value); } attributeChangedCallback() { this.calls += 1; } } customElements.define("tea-timer", TeaTimer); const timer = document.querySelector("tea-timer"); const observer = new MutationObserver(() => {}); observer.observe(timer, { attributes: true }); for (let left = 59; left >= 0; left -= 1) timer.left = left; console.log("Mutation records:", observer.takeRecords().length); console.log("Callback calls:", timer.calls);</script>- Lines 8 to 10 are a setter that reflects
leftto an attribute. - Lines 12 to 14: the callback counts how often it runs.
- Lines 19 and 20 start a
MutationObserverthat watches the timer's attributes. - Line 21 sets the property 60 times, like a timer counting down from 59 to 0.
- Line 22 asks the observer for its records with
takeRecords(). It printsMutation records: 60. Line 23 printsCallback calls: 60.
Every set did three things. It changed the HTML, which CSS and DevTools then see. It ran the callback. And it gave every observer a record. Change line 9 to this.leftNow = value;, a plain property, and both lines print 0. The Observers lesson covers MutationObserver in full.
attributeChangedCallback() and gives every MutationObserver a record. Sixty sets a minute means sixty of each.That's why web.dev says not to reflect values that change very often, like a video's current time. Big data is the other case. A list of 50 teas would have to become text on every change. web.dev's checklist says to take rich data, like objects and arrays, only as properties, and not to reflect it.
Leaf and Kettle has a small shop window. Ravi puts a few clear signs in it: today's tea, its price, and "open". Everyone walking past reads them. The big boxes stay in the stockroom, out of sight. He doesn't empty the stockroom into the window. And he doesn't repaint the window every minute.
- In real life: A sign in the window
- In JavaScript: A reflected attribute, like
minutes="5" - In real life: People walking past who read the signs
- In JavaScript: CSS selectors, DevTools, and observers
- In real life: The boxes in the stockroom
- In JavaScript: Objects and arrays, kept in properties
- In real life: Repainting the window every minute
- In JavaScript: Reflecting a value that changes every second
So which ones should reflect? web.dev's checklist and Cory LaViska, who created the Shoelace library, give rules like these:
- Reflect short settings people write in HTML: text, numbers, and on or off values.
- Reflect values the page styles, like a
sizethat CSS selects withtea-cup[size="large"]. - Reflect state people want to see in DevTools, like
openordisabled. - Don't reflect objects, arrays, long content, or values that change many times a second.
Sort these values into the two groups:
- A tea label's
name, likeGreen tea - A tea label's
minutes - A cup's
size, which the page's CSS styles - Whether a tea menu is
open - A cup's
blend, an object with a tea and its extras - A menu's
teas, a list of 50 teas - The seconds left on a brewing timer
- A video player's current time
Sort each value by whether its property should reflect to an attribute.
Two more rules. First, don't add an attribute the page didn't write, just to show a default. Lit's docs call attributes "input to the element from its owner", and say to reflect "sparingly". Lesson 3.2 showed that a constructor must not add attributes anyway.
Second, some state only exists for styling, like "busy". For that, custom states and the :state() selector fit better than a made-up attribute. Lesson 12.3 covers them.
How do you convert attribute strings to other types?
The getter is where text turns into a value. For numbers, the reflecting label used Number(). It's strict: the whole text has to be a number. Here is what it makes of text an attribute might hold:
const texts = ["4", " 4 ", "", "four", "4 min", null];
for (const text of texts) {
console.log(JSON.stringify(text), "gives", Number(text));
}- Line 1 lists six values. The last,
null, is whatgetAttribute()gives when there's no attribute. - Line 3 prints each one, then what
Number()makes of it.
It prints "4" gives 4 and " 4 " gives 4, so spaces around a number are fine. It prints "" gives 0 and null gives 0: an empty or missing attribute counts as zero. And "four" and "4 min" both give NaN. NaN means "not a number". It's a number value that says the text couldn't be read.
Number() works like a pocket calculator. Type 4, and it shows 4. Spaces don't matter. Type nothing, and the screen shows 0. It only knows digits. If a word gets in, it shows "Error".
- In real life: Typing the digits 4
- In JavaScript:
Number("4")gives 4 - In real life: A blank screen that shows 0
- In JavaScript:
Number("")andNumber(null)give 0 - In real life: "Error" when a word gets in
- In JavaScript:
Number("four")givesNaN
Try your own text:
label.setAttribute("minutes", "4");
console.log(label.minutes);label.minutes is 4
The label shows: Brew for 4 minutes
The whole text is a number, so Number() gives that number.
Why it matters: 0 and NaN are both numbers, so a bad attribute won't throw. The label just shows Brew for NaN minutes. Lesson 5.2 adds a default and handles bad input, as built-in elements do.
The other way is easier. setAttribute() turns any value into text by itself, so setAttribute("minutes", 5) stores "5". You only need to help when that text isn't what you want.
Dates
A date is one of those. Its own text is long, and it depends on the reader's time zone. So write a date out in a short, standard form, and read it back with new Date():
const packed = new Date("2026-12-01");
const text = packed.toISOString().slice(0, 10);
console.log(text);
console.log(new Date(text).getTime() === packed.getTime());- Line 1 makes a date for December 1, 2026.
- Line 2 turns it into text.
toISOString()gives the international format, andslice(0, 10)keeps just the day. - Line 3 prints
2026-12-01. That's the text a setter would write. - Line 4 reads it back with
new Date(). It printstrue: the same moment as line 1.
So a cup's packed getter would return new Date(this.getAttribute("packed")). Its setter would write date.toISOString().slice(0, 10).
JSON in an attribute
Some components put a list in an attribute as JSON, a text format for objects and arrays. They read it with JSON.parse(). It works, but look at what happens:
<tea-menu teas='["Green tea", "Mint tea"]'></tea-menu> <script> class TeaMenu extends HTMLElement { get teas() { return JSON.parse(this.getAttribute("teas")); } connectedCallback() { this.textContent = this.teas.join(", "); } } customElements.define("tea-menu", TeaMenu); const menu = document.querySelector("tea-menu"); menu.teas.push("Oolong"); console.log(menu.teas.length); console.log(menu.teas === menu.teas);</script>- Line 1 writes two teas as JSON. It needs single quotes outside, because JSON uses double quotes inside.
- Lines 5 to 7: the getter turns the text into an array, on every read.
- Line 15 adds Oolong to the list.
- Line 16 prints
2. Oolong isn't there. - Line 17 prints
false. Two reads gave two different arrays.
Each read of menu.teas makes a new array from the text. Line 15 changed one of those copies, and the copy was thrown away. A typo in the HTML is worse: JSON.parse() throws a SyntaxError every time the getter runs.
So keep lists and objects in properties. If HTML is the only way in, split the data into simple attributes. MIT's web design course shows min="1" max="5" in place of range='{"min": 1, "max": 5}'. Lit's default converter does read arrays and objects with JSON.parse(). But its docs advise against reflecting them.
Giving the tea kit's label its properties
Back to Asha's menu. Ravi updates the kit's tea-label.js with what this lesson showed. Here is her page again, unchanged, with the new kit:
<p><tea-label name="Green tea" minutes="4"></tea-label></p> <script type="module"> await import("./tea-kit/index.js"); const label = document.querySelector("tea-label"); label.minutes = 5; console.log(label.textContent); console.log(label.getAttribute("minutes"), label.minutes);</script>Open the tea-kit/tea-label.js tab:
- Lines 4 to 10 are
name. The getter reads the attribute, and the setter writes it. - Lines 12 to 18 are
minutes. The getter turns the text into a number. - Lines 25 to 28 are the callback. It only draws, so the attribute stays the one source, and nothing can loop.
- Line 21 runs the upgrade-property pattern from lesson 4.2 for both names. Line 38 draws the text through the getters.
In the index.html tab, line 7 now prints Green tea: brew for 5 minutes. Line 8 prints 5 5: the attribute and the property agree. Asha's line 6 works.
The pattern from lesson 4.2 still matters. This page sets the name before the kit loads:
<p><tea-label minutes="3"></tea-label></p> <script type="module"> const label = document.querySelector("tea-label"); label.name = "Oolong"; await import("./tea-kit/index.js"); console.log(label.getAttribute("name"), label.textContent);</script>Line 5 sets name while the label still waits for its class. Line 6 loads the kit. Line 7 prints Oolong Oolong: brew for 3 minutes. The attribute and the text both have the early name.
Why it matters: Asha's script, a framework that sets properties, and plain HTML now all work the same way. And CSS can style a label by its minutes.
Common mix-ups
- "A property and an attribute with the same name are linked." No. On your own element, they have nothing to do with each other until your class writes a getter and a setter. The overview's label had both, with different values.
- "setAttribute("minutes", 5) stores the number 5." No. Attributes are always text. It stores
"5", and your getter turns it back into a number. - "An input's value attribute is what the user typed." No. It's the default. The
valueproperty is the live text, anddefaultValuereflects the attribute. - "A setter that writes the attribute always loops." No. It loops only if the callback calls the setter back. If the callback just draws, nothing loops.
- "Reflect every property, to be safe." No. Each reflected change costs an attribute change, a callback, and observer records. Keep objects, arrays, and fast-changing values as properties.
- "Objects belong in attributes, as JSON." No. It's slow, needs careful quotes, and makes a new copy on every read. Use a property.
- "Every styling hook needs a reflected attribute." No. For state only the component sets, like busy, custom states and
:state()fit better.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
What does line 4 print?
const box = document.createElement("input");
box.type = "checkbox";
box.checked = true;
console.log(box.hasAttribute("checked"), box.defaultChecked);false false. Line 3 ticks the box through checked, which reflects nothing. So there's still no checked attribute, and defaultChecked, which reads that attribute, is false.
What do lines 3 and 5 print?
const label = document.createElement("tea-label");
label.setAttribute("minutes", "");
console.log(Number(label.getAttribute("minutes")));
label.setAttribute("minutes", "three");
console.log(Number(label.getAttribute("minutes")));0, then NaN. An empty attribute gives 0, which looks like a real value. three is a word, so Number() can't read it.
The CSS makes a large cup's text bigger. Line 14 sets cup.size, but the class has no size property, so the console prints small. Add a size property that reflects. What does it print then?
<style> tea-cup[size="large"] { font-size: 2em; }</style><tea-cup size="small">Green tea</tea-cup> <script> class TeaCup extends HTMLElement { // Add a size property here. Its getter reads the size attribute. // Its setter writes it. } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); cup.size = "large"; console.log(cup.getAttribute("size"));</script><style> tea-cup[size="large"] { font-size: 2em; }</style><tea-cup size="small">Green tea</tea-cup> <script> class TeaCup extends HTMLElement { get size() { return this.getAttribute("size"); } set size(value) { this.setAttribute("size", value); } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); cup.size = "large"; console.log(cup.getAttribute("size"));</script>With the setter, cup.size = "large" writes the attribute instead of making a plain property. The console prints large, and the CSS rule on line 2 makes the text twice as big.
Line 15 should print 6, but it prints 51. Find the bug and fix it. What does line 15 print then?
<tea-label minutes="5"></tea-label> <script> class TeaLabel extends HTMLElement { get minutes() { return this.getAttribute("minutes"); } set minutes(value) { this.setAttribute("minutes", value); } } customElements.define("tea-label", TeaLabel); const label = document.querySelector("tea-label"); console.log(label.minutes + 1);</script><tea-label minutes="5"></tea-label> <script> class TeaLabel extends HTMLElement { get minutes() { return Number(this.getAttribute("minutes")); } set minutes(value) { this.setAttribute("minutes", value); } } customElements.define("tea-label", TeaLabel); const label = document.querySelector("tea-label"); console.log(label.minutes + 1);</script>The getter gave back the text "5", and "5" + 1 joins two texts into "51". With Number() on line 6, the getter gives 5, and line 15 prints 6.
Lines 17 to 19 set the same size three times. How many records does line 20 count?
<tea-cup></tea-cup> <script> class TeaCup extends HTMLElement { get size() { return this.getAttribute("size"); } set size(value) { this.setAttribute("size", value); } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); const observer = new MutationObserver(() => {}); observer.observe(cup, { attributes: true }); cup.size = "large"; cup.size = "large"; cup.size = "large"; console.log(observer.takeRecords().length);</script>3. Each set writes the attribute, even with the same value, so the observer gets three records. To skip repeats, the setter can check first: if (this.getAttribute("size") === value) return;. Then the count is 1.
The kit's timer only reads a seconds attribute. This page sets timer.seconds = 3 instead, so line 6 prints null 0 s. Give the timer a seconds property that reflects. What does line 6 print then?
<script type="module"> await import("./tea-kit/index.js"); const timer = document.createElement("tea-timer"); timer.seconds = 3; document.body.append(timer); console.log(timer.getAttribute("seconds"), timer.textContent);</script>export class TeaTimer extends HTMLElement { #controller = null; get seconds() { return Number(this.getAttribute("seconds")); } set seconds(value) { this.setAttribute("seconds", value); } connectedCallback() { if (this.#controller) return; this.#controller = new AbortController(); let left = Number(this.getAttribute("seconds")); this.textContent = `${left} s`; const interval = setInterval(() => { left -= 1; this.textContent = left > 0 ? `${left} s` : "Ready"; if (left === 0) clearInterval(interval); }, 1000); this.#controller.signal.addEventListener("abort", () => clearInterval(interval)); } async disconnectedCallback() { await Promise.resolve(); if (this.isConnected) return; this.#controller?.abort(); this.#controller = null; } connectedMoveCallback() {}} customElements.define("tea-timer", TeaTimer);Now line 4 writes the attribute, so connectedCallback() reads 3 when line 5 adds the timer. Line 6 prints 3 3 s. The countdown stays a plain variable: it changes every second, so it shouldn't reflect.
Check your understanding
For each question, ask where the value lives: in the attribute, in a property, or in both.
Question 1 of 7Why does the overview's label still say 4 minutes after line 6 sets
label.minutes = 5?Read the code, then predict<p><tea-label name="Green tea" minutes="4"></tea-label></p> <script type="module"> await import("./tea-kit/index.js"); const label = document.querySelector("tea-label"); label.minutes = 5; console.log(label.textContent); console.log(label.getAttribute("minutes"), label.minutes); </script>Choose an answer to see the explanation.
Question 2 of 7In the HTML Standard, what does it mean for a property to reflect an attribute?
Choose an answer to see the explanation.
Question 3 of 7You type Mint tea into
<input value="Green tea">. What doesinput.getAttribute("value")give now?Choose an answer to see the explanation.
Question 4 of 7What does line 23 of the reflecting tea label print?
Read the code, then predict<p><tea-label minutes="4"></tea-label></p> <script> class TeaLabel extends HTMLElement { static observedAttributes = ["minutes"]; get minutes() { return Number(this.getAttribute("minutes")); } set minutes(value) { this.setAttribute("minutes", value); } attributeChangedCallback() { this.textContent = `Brew for ${this.minutes} minutes`; } } customElements.define("tea-label", TeaLabel); const label = document.querySelector("tea-label"); label.minutes = 5; console.log(label.minutes, typeof label.minutes); console.log(label.getAttribute("minutes")); </script>Choose an answer to see the explanation.
Question 5 of 7Which design can't loop, even with no guard in the callback?
Choose an answer to see the explanation.
Question 6 of 7Which of these should stay a property, with no attribute?
Choose an answer to see the explanation.
Question 7 of 7What does line 16 of the JSON menu print?
Read the code, then predict<tea-menu teas='["Green tea", "Mint tea"]'></tea-menu> <script> class TeaMenu extends HTMLElement { get teas() { return JSON.parse(this.getAttribute("teas")); } connectedCallback() { this.textContent = this.teas.join(", "); } } customElements.define("tea-menu", TeaMenu); const menu = document.querySelector("tea-menu"); menu.teas.push("Oolong"); console.log(menu.teas.length); console.log(menu.teas === menu.teas); </script>Choose an answer to see the explanation.
Key takeaways
- Attributes are text in the HTML. CSS, DevTools, the element's HTML, and observers can all see them.
- Properties are values on the object, of any type. Only JavaScript sees them.
- A reflecting property reads and writes its attribute, like
id. An input'svalueattribute is only the default. - The simplest design keeps the attribute as the one source: the getter reads it, the setter writes it, and the callback only draws.
- A private field as the source needs a guard in the callback, or it loops.
- Reflect short settings and styling hooks. Keep objects, arrays, and fast-changing values as properties.
- Convert in the getter:
Number()for numbers, short ISO text for dates. Keep JSON out of attributes.
Remember the one-liner.
Attributes are text for HTML, and properties are values for JavaScript: reflect the simple ones by reading and writing the attribute, and let the callback only draw.
Sources
The facts on this page come from these standards, docs, and posts:
- Attribute reflection, MDN.
- HTML Standard: Reflecting content attributes in IDL attributes, WHATWG.
- HTML Standard: The input element, WHATWG.
- HTML attributes vs DOM properties, Jake Archibald.
- Modern Web Guidance: Custom Elements, Chrome for Developers.
- Custom element best practices, web.dev.
- Custom Elements v1: Reusable Web Components, web.dev.
- Lit: Reactive properties, Lit.
- Reflection and Custom States in Web Components, Cory LaViska.
- 6.4500 lecture: Component-driven development, MIT.
- MutationObserver: takeRecords() method, MDN.
- Number() constructor, MDN.
- JSON.parse(), MDN.
Coming next: Boolean, number, and enum attributes. Handle on and off attributes, numbers, fixed sets of values, defaults, and bad input, the way built-in elements do.