Boolean, number, and enum attributes
Handle web component boolean attributes, enums, and numbers like built-in elements: presence means on, keywords fall back, and bad text gets a default.
- 01Write boolean attributes that act like disabledRead them with hasAttribute(), write them with toggleAttribute(), and never turn one off with the text "false".
- 02Give enumerated attributes their defaultsMatch a few keywords in any case, and fall back to a missing value default and an invalid value default.
- 03Read numbers and JSON without throwingUse HTML's rules for whole numbers and decimals, limits like non-negative, and a fallback for broken JSON.
How should a web component handle boolean, enum, and number attributes?
Asha is adding an order button to the Leaf and Kettle menu. Green tea is in stock today. To be extra sure the button works, she writes disabled="false". She opens the page. The button is grey, and it can't be clicked.
Ravi, who writes the tea kit, has the same kind of question coming. He wants a cup that can be iced, three cup sizes, and a timer with a number of seconds. What should iced="false" mean? What about size="huge", or seconds="90 s"?
Read each attribute the way built-in elements do. A boolean attribute is on whenever it's there, even with the text false. An enumerated attribute takes one of a few keywords, in any case, and falls back to a default. A number attribute is read with HTML's own rules, and falls back to a default too. Then anyone who knows HTML already knows how your component behaves.
Here is Asha's button:
<button disabled="false">Order green tea</button> <script> const button = document.querySelector("button"); console.log(button.disabled); console.log(button.getAttribute("disabled"));</script>- Line 1 writes the button with
disabled="false". - Line 5 prints
true. The button is disabled. - Line 6 prints
false. That's the attribute's text, and nothing reads it.
The browser asked one question: is there a disabled attribute? Yes. So the button is disabled. The text after the equals sign never mattered.
disabled is there. The text false never gets read, so the third button is disabled too.When a tea runs out, Ravi puts a red sticker on its line of the printed menu. Customers see the sticker and pick another tea. Nobody reads what's written on it. Even a sticker that said "not sold out" would stop them. To bring the tea back, Ravi peels the sticker off.
- In real life: The sticker on the menu
- In JavaScript: The attribute being there, like
disabled - In real life: The words written on the sticker
- In JavaScript: The attribute's text, like
"false", which nobody reads - In real life: Peeling the sticker off
- In JavaScript:
removeAttribute(): the only way to say off
Built-in elements read attributes by fixed rules, and your component should use the same ones. A boolean is on when the attribute is there. An enumerated attribute gives a keyword or a default. A number is read with HTML's rules, or gets a default. And a getter never throws.
In lesson 5.1, the tea label's minutes getter turned text into a number with Number(). It left two problems open. An empty attribute gave 0, and 4 min gave NaN. This lesson fixes both, with the rules from the HTML Standard.
Why does disabled="false" still disable a button?
Because disabled is a boolean attribute: an attribute that is either there or not. The HTML Standard says it plainly. When the attribute is there, the value is true. When it's missing, the value is false. It even says the values "true" and "false" aren't allowed on these attributes. To say false, you leave the attribute out.
Chrome follows that rule for any text. This loop writes four texts into disabled, then removes it:
const button = document.createElement("button");
for (const text of ["", "disabled", "false", "no"]) {
button.setAttribute("disabled", text);
console.log(JSON.stringify(text), button.disabled);
}
button.removeAttribute("disabled");
console.log("removed", button.disabled);- Line 3 writes each text into the attribute.
- Line 4 prints the text and
button.disabled. All four printtrue:"","disabled","false", and"no". - Line 6 removes the attribute. Line 7 prints
removed false.
People write it two ways: just the name, <button disabled>, or the name twice, disabled="disabled". Both mean on. So does every other text.
Reading and writing the property
A built-in boolean property reflects its attribute both ways. Set the property to true, and the browser writes the attribute with empty text. Set it to false, and the attribute goes away:
const details = document.createElement("details");
details.open = true;
console.log(details.outerHTML);
details.open = false;
console.log(details.outerHTML);
details.open = "no";
console.log(details.outerHTML);- Line 2 sets
opentotrue. Line 3 prints<details open=""></details>. - Line 4 sets it to
false. Line 5 prints<details></details>. The attribute is gone. - Line 6 sets it to the text
"no". Line 7 prints<details open=""></details>again.
Line 6 is the surprise. The setter first turns the value into true or false, the way Boolean() does. Any text that isn't empty counts as true. Jake Archibald shows the same thing with details.open = "hello".
One built-in is a little different. The HTML Standard lists the hidden attribute as an enumerated attribute, the kind the next section explains. It has one extra keyword, until-found. Any other text still hides the element, false included.
A boolean attribute on your own element
Your component gets none of this for free. Write the getter with hasAttribute(), and the setter with toggleAttribute():
<tea-cup iced>Green tea</tea-cup> <script> class TeaCup extends HTMLElement { get iced() { return this.hasAttribute("iced"); } set iced(value) { this.toggleAttribute("iced", Boolean(value)); } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); console.log(cup.iced); cup.iced = false; console.log(cup.iced, cup.outerHTML); cup.iced = "no"; console.log(cup.iced, cup.outerHTML);</script>- Line 1 writes a cup with
icedand no text. - Lines 5 to 7 are the getter, the function that runs when code reads
cup.iced.hasAttribute()givestruewhen the attribute is there. - Lines 8 to 10 are the setter.
toggleAttribute(name, force)adds the attribute whenforceis true, and removes it whenforceis false. - Line 15 prints
true. - Line 16 sets
icedtofalse. Line 17 printsfalse <tea-cup>Green tea</tea-cup>. The attribute is gone. - Line 18 sets it to
"no". Line 19 printstrue <tea-cup iced="">Green tea</tea-cup>, just likedetails.open.
Line 9 turns the value into true or false with Boolean() first. That matters for undefined. Called with undefined, toggleAttribute() acts as if it got no second argument, and flips the attribute. With Boolean(), cup.iced = undefined turns the cup off, as it should.
Chrome's custom elements guidance shows this same pair, with a warning beside it: never set a boolean attribute to "false". MDN's toggleAttribute() page explains the second argument.
Turning a boolean attribute off
The warning matters most in JavaScript. setAttribute() turns every value into text. So this line removes nothing:
const button = document.createElement("button");
button.setAttribute("disabled", false);
console.log(button.getAttribute("disabled"), button.disabled);Line 2 passes the value false. Line 3 prints false true. The attribute now holds the text false, and the button is still disabled. To turn it off, call removeAttribute("disabled"), call toggleAttribute("disabled", false), or set the property to false.
This rule shapes names too. Lit's docs say a boolean attribute has to start out false. If it starts out true, HTML has no way to turn it off. That's why the platform has disabled, not enabled. So the tea kit's label will get sold-out, not in-stock.
Pick a text, and watch a real button and the cup side by side:
<button>Order</button><tea-cup></tea-cup> <script src="tea-cup.js"></script><script> const button = document.querySelector("button"); const cup = document.querySelector("tea-cup"); console.log("button.disabled is", button.disabled); console.log("cup.iced is", cup.iced);</script>There's no attribute, so the button works and the cup is hot. Leaving the attribute out is the only way to say off.
Every choice but No attribute disables the button and ices the cup. The cup follows the same rule as the button, because its getter only calls hasAttribute().
What is an enumerated attribute?
Some attributes take one word from a short list. An input's type is one. It takes text, email, number, and about twenty more. The HTML Standard calls these enumerated attributes, and each word in the list a keyword.
const input = document.createElement("input");
for (const text of ["email", "EMAIL", "e-mail"]) {
input.setAttribute("type", text);
console.log(JSON.stringify(text), "gives", input.type);
}
input.removeAttribute("type");
console.log("no attribute gives", input.type);- Line 3 writes three texts into
type. - Line 4 prints
"email" gives emailand"EMAIL" gives email. Keywords ignore case. - Then it prints
"e-mail" gives text.e-mailisn't a keyword, so the input falls back totext. - Line 6 removes the attribute. Line 7 prints
no attribute gives text.
The HTML Standard's rules for these attributes have three parts:
- Case: a keyword matches with any mix of capital and small letters, A to Z. The standard calls this ASCII case-insensitive. Spaces still count, so
" email"isn't a keyword. - The missing value default: what the attribute means when it isn't written at all.
- The invalid value default: what it means for any text that isn't a keyword.
Leaf and Kettle sells three sizes: small, medium, and large. A customer who shouts "LARGE!" gets a large. One who asks for a "huge" doesn't get an argument. The barista pours the house size, a medium. One who names no size at all gets a medium too.
- In real life: The three sizes on the board
- In JavaScript: The keywords:
small,medium, andlarge - In real life: A customer who shouts "LARGE!"
- In JavaScript:
size="LARGE": keywords match in any case - In real life: Asking for a "huge"
- In JavaScript: Text that isn't a keyword: the invalid value default
- In real life: Saying no size at all
- In JavaScript: No attribute: the missing value default
Each attribute picks its own defaults, and they don't always match. Read each row across. Each cell is what the property gives:
| Attribute | When it's missing | When the word is unknown | When it's empty |
|---|---|---|---|
<input type>, read with input.type | "text" | "text" | "text" |
dir, read with p.dir | "" | "" | "" |
crossorigin, read with img.crossOrigin | null | "anonymous" | "anonymous" |
popover, read with div.popover | null | "manual" | "auto" |
So dir has no defaults at all, and its property gives an empty string. crossorigin reads an unknown word as anonymous. And popover gives three different answers. Its empty text has a third default of its own, which the standard calls the empty value default.
The property gives a keyword, and the attribute keeps the text
The standard says these properties are "limited to only known values". Their getter only gives back keywords. Their setter writes whatever you give it:
const input = document.createElement("input");
input.type = "Nonsense";
console.log(input.getAttribute("type"));
console.log(input.type);- Line 2 sets the property to
Nonsense. - Line 3 prints
Nonsense. The setter wrote the text as it was. - Line 4 prints
text. The getter turned it into the default.
MDN's attribute reflection guide shows the same with dir: dir="RTL" gives rtl from the property and RTL from getAttribute(). Why it matters: the HTML keeps what the page wrote, and your code always gets a keyword it can trust.
An enumerated attribute on your own element
Here is a cup with three sizes. Its getter follows all three rules:
<tea-cup size="LARGE"></tea-cup><tea-cup size="huge"></tea-cup><tea-cup></tea-cup> <script> class TeaCup extends HTMLElement { static sizes = ["small", "medium", "large"]; get size() { const text = this.getAttribute("size"); if (text === null) return "medium"; const keyword = text.toLowerCase(); return TeaCup.sizes.includes(keyword) ? keyword : "medium"; } set size(value) { this.setAttribute("size", value); } connectedCallback() { this.textContent = `A ${this.size} cup. `; } } customElements.define("tea-cup", TeaCup);</script>- Lines 1 to 3 write three cups:
LARGE,huge, and no size. - Line 7 lists the keywords.
- Line 10 is the missing value default. No attribute gives
medium. - Line 11 lowercases the text, so
LARGEbecomeslarge. - Line 12 gives back the keyword if it's in the list. If not, it gives the invalid value default,
medium. - Lines 14 to 16 are the setter. Like
input.type, it writes the text as it is.
The result shows A large cup. A medium cup. A medium cup.
LARGE matches large, because keywords ignore case. huge gets the invalid value default, and a cup with no size gets the missing value default. Here both defaults are medium.Now try any text. The playground runs the cup's rule, and compares it with an input's type and a CSS selector:
cup.setAttribute("size", "LARGE");
console.log(cup.size);cup.size gives "large"
An input with this type gives "text"
tea-cup[size="large"] doesn't match
Keywords ignore the case of A to Z, so this reads as large. CSS doesn't: tea-cup[size="large"] needs the exact text.
Try LARGE. The getter gives large, but tea-cup[size="large"] doesn't match. CSS compares the text exactly. The section on defaults shows how to style sizes anyway.
When true and false are keywords
Not every on-or-off attribute is boolean. A few enumerated attributes have the keywords true and false. For those, "false" really means false. Sort these built-in attributes:
- A button's
disabled - A details element's
open - A checkbox's
checked - An input's
type - The
dirattribute - The
popoverattribute - The
draggableattribute - The
contenteditableattribute
Sort each attribute by how the browser reads it.
draggable and contenteditable are the ones to remember. draggable="false" turns dragging off, because false is one of its keywords.
How does the browser read number attributes?
A number attribute is still text, so something has to read the digits. Built-in elements use the HTML Standard's rules for parsing integers. An integer is a whole number. An ordered list's start uses these rules. It sets the list's first number, and falls back to 1:
const list = document.createElement("ol");
for (const text of ["3", " 3", "3rd", "3.9", "three", ""]) {
list.setAttribute("start", text);
console.log(JSON.stringify(text), "gives", list.start);
}- Line 3 writes six texts into
start. - Line 4 prints
"3" gives 3and" 3" gives 3. Spaces at the start are skipped. - Then
"3rd" gives 3and"3.9" gives 3. Reading stops at the first character that isn't a digit. - Then
"three" gives 1and"" gives 1. No digits at the start means no number. So the list uses its default, 1.
The rules are short. In plain words:
- Skip any spaces, tabs, and line breaks at the start.
- Read a minus sign if there is one. A plus sign is skipped.
- If the next character isn't a digit, 0 to 9, there's no number.
- Read the digits. Stop at the first character that isn't one, and ignore the rest.
" 5px" and "5 minutes" both give 5.Customers leave notes for Ravi, like "2 sugars, please". Ravi reads the 2 and stops at the first letter. The rest is polite words, not an amount. A note that says "lots of sugar" has no number at the start. So Ravi makes the house version, with no sugar.
- In real life: Reading the 2 and stopping at the first letter
- In JavaScript: HTML's rules: read the digits, ignore the rest
- In real life: A note that says "lots of sugar"
- In JavaScript: Text with no digits at the start: no number
- In real life: The house version
- In JavaScript: The attribute's default
JavaScript's own tools read numbers differently. Number() needs the whole text to be a number. parseInt() is closer to HTML. But it gives NaN where HTML gives a default. Read each row across:
| What the attribute says | Number(text) gives | parseInt(text, 10) gives | HTML's rules give |
|---|---|---|---|
"5" | 5 | 5 | 5 |
" 5" | 5 | 5 | 5 |
"5px" | NaN | 5 | 5 |
"5.9" | 5.9 | 5 | 5 |
"" | 0 | NaN | No number, so the default |
"five" | NaN | NaN | No number, so the default |
"0x10" | 16 | 0 | 0 |
"1e3" | 1000 | 1 | 1 |
Two rows stand out. "5px" is NaN to Number(), and 5 to HTML. And the empty text is 0 to Number(), which looks like a real value. HTML finds no number there. Always give parseInt() the base, 10, too. Without it, parseInt("0x10") reads the text as a hexadecimal number and gives 16, as MDN's parseInt() page explains. The JavaScript path compares these tools in Type conversion.
Numbers that can't be negative
Some numbers make no sense below zero. One is maxlength, the most characters a text box takes. The standard marks its property "limited to only non-negative numbers". The getter gives a default for a negative number, and the setter refuses one:
const input = document.createElement("input");
console.log(input.maxLength);
input.setAttribute("maxlength", "-5");
console.log(input.maxLength);
try {
input.maxLength = -5;
} catch (error) {
console.log(error.name);
}- Line 2 prints
-1. With no attribute,maxLengthgives the standard's default for these properties, -1. - Line 3 writes
-5into the attribute. Line 4 prints-1again. A negative number gets the default. - Line 6 sets the property to -5. The setter throws, and line 8 prints
IndexSizeError. The attribute doesn't change.
An IndexSizeError is a kind of DOMException, the error type the browser uses for its own APIs. Some numbers must even be above zero, like a text area's cols, its width in characters. For those, 0 gets the default too: cols="0" gives 20.
Decimals
For decimals, the standard has the rules for parsing floating-point number values. They work like the integer rules, plus a decimal point and an exponent, like 1e3 for 1000. A progress bar's max uses them. It must be above 0, and falls back to 1:
const bar = document.createElement("progress");
for (const text of ["2.5", "2.5kg", ".5", "0", "-1", "full"]) {
bar.setAttribute("max", text);
console.log(JSON.stringify(text), "gives", bar.max);
}- Line 4 prints
"2.5" gives 2.5and"2.5kg" gives 2.5. The letters after the number are ignored. - Then
".5" gives 0.5. A number can start with the point. - Then
"0" gives 1,"-1" gives 1, and"full" gives 1. None is above 0, so the bar uses its default.
A number attribute on your own element
Here is a cup with sugar, a whole number of spoons. It can't be negative, and its default is 0:
<tea-cup sugar="2 spoons"></tea-cup><tea-cup sugar="-1"></tea-cup><tea-cup sugar="lots"></tea-cup> <script> function parseInteger(text) { const match = /^[\t\n\f\r ]*([+-]?\d+)/.exec(text); return match === null ? null : Number(match[1]); } class TeaCup extends HTMLElement { get sugar() { const value = parseInteger(this.getAttribute("sugar") ?? ""); return value !== null && value >= 0 ? value : 0; } connectedCallback() { this.textContent = `Sugar: ${this.sugar}. `; } } customElements.define("tea-cup", TeaCup);</script>- Lines 6 to 9 are the integer rules as a function.
- Line 7 is a regular expression, a pattern for text. Read it piece by piece.
^is the start of the text.[\t\n\f\r ]*is any spaces, tabs, and line breaks.[+-]?is a sign, if there is one. And\d+is one or more digits. - Line 8 gives
nullwhen the pattern finds no number. Otherwise it gives the number.Number()is safe here, because the match holds only a sign and digits. - Line 13 reads the attribute.
?? ""turns a missing attribute into empty text. - Line 14 gives the number if it's 0 or more, and the default, 0, if not.
The result shows Sugar: 2. Sugar: 0. Sugar: 0. The JavaScript path teaches patterns in Patterns & flags.
Type any text into the cup's sugar, and compare five ways to read it:
cup.setAttribute("sugar", "2 spoons");
console.log(cup.sugar);HTML's integer rules: 2
Number(text): NaN
parseInt(text, 10): 2
The cup's sugar, default 0: 2
HTML's decimal rules: 2
HTML's rules read the digits at the start and stop at the first character that isn't one. Number() needs the whole text to be a number.
Try 2.9. HTML's integer rules give 2, and its decimal rules give 2.9. Try 0x10. Number() gives 16, and HTML gives 0.
Should a web component take JSON in an attribute?
Lesson 5.1 said to keep lists and objects in properties. A list in an attribute has to become text, be quoted with care, and be parsed again after every change. A property is still the right default.
But sometimes the data has to be in the HTML, like a short list a server writes into the page before any script runs. Libraries allow it. Lit's default converter reads an Array or Object attribute with JSON.parse(). If you do it by hand, do two things. Parse once, when the attribute changes. And never throw:
<tea-menu teas='["Green tea", "Mint tea"]'></tea-menu><tea-menu teas='["Green tea", Mint tea]'></tea-menu> <script> class TeaMenu extends HTMLElement { static observedAttributes = ["teas"]; #teas = []; get teas() { return this.#teas; } attributeChangedCallback(name, oldValue, newValue) { let teas = []; try { teas = JSON.parse(newValue); } catch { console.warn("teas isn't valid JSON"); } this.#teas = Array.isArray(teas) ? teas : []; this.textContent = this.#teas.join(", ") || "No teas yet"; } } customElements.define("tea-menu", TeaMenu); const [menu] = document.querySelectorAll("tea-menu"); console.log(menu.teas.length, menu.teas === menu.teas);</script>- Line 2 has a typo.
Mint teahas no quotes, so the text isn't valid JSON. - Line 6 observes
teas, so the callback runs when it changes. - Lines 13 to 17 try to parse the text. If
JSON.parse()throws, thecatchblock warns in the console, andteasstays an empty list. - Line 18 keeps the result only if it's an array. Text like
5is valid JSON, but it isn't a list. - Line 25 prints
2 true. There are two teas, and every read gives the same array.
The result shows Green tea, Mint tea and No teas yet. The console shows the warning, teas isn't valid JSON. Without the try, the second menu would throw a SyntaxError and never draw its text.
Lit makes the same choice. Its converter's source catches the error and gives null. A comment says why: elements "don't normally complain on being mis-configured". For try and catch in full, see try, catch & finally in the JavaScript path.
Compare lesson 5.1's menu. Its getter parsed on every read, so menu.teas === menu.teas was false. Here it's true, because the parsed list waits in a private field.
What should a getter return for a missing or bad value?
Every rule so far ends the same way. When the text is missing or makes no sense, the built-in element uses a default. It doesn't throw, and it doesn't change the attribute. That gives your own getters a short list of rules:
- Return a value of the right type every time: a boolean, a keyword, or a number.
- Use the default for missing text, and for bad text.
- Never throw from a getter. Code reads properties all the time: your own drawing code, frameworks, and other people's scripts.
- Leave the attribute as the page wrote it.
<input type="Nonsense">keeps its text, and only the property cleans it up.
A setter may refuse a value that can never work, the way maxLength refuses -5. Most setters just write the text, and let the getter clean it up.
huge, and the HTML keeps it.One slip on the kitchen rail is smudged, and the cook can't read the size. She doesn't stop the kitchen. She doesn't rewrite the slip either. She makes the house size and leaves the slip as it is, so the waiter can check it later.
- In real life: The smudged slip
- In JavaScript: Bad attribute text, like
size="huge" - In real life: Making the house size
- In JavaScript: The getter returning the default
- In real life: Not stopping the kitchen
- In JavaScript: The getter never throwing
- In real life: Leaving the slip as it is
- In JavaScript: Not rewriting the attribute
Burton Smith, who builds a component library, puts this on his team's review checklist. Attributes and properties have to work "when set, unset, and poorly set". His model is the built-in input: type="rubbish" still gives a text box.
Here is every kind from this lesson. Read each row across:
| Kind of attribute | When it's missing | When the text is bad | Read it with |
|---|---|---|---|
Boolean, like iced | It's off. | There's no bad text. Any text means on. | hasAttribute() |
Enumerated, like size | The missing value default. | The invalid value default. | toKeyword() |
Whole number, like start | The default. | The default. Text after the digits is ignored. | toInteger() |
Whole number, 0 or more, like sugar | The default. | The default, and for a negative number too. | toNonNegativeInteger() |
Decimal, like max | The default. | The default. Text after the number is ignored. | toFloat() |
JSON, like teas | The fallback. | The fallback, and no error is thrown. | toJson() |
Putting the rules in one file
The tea kit will use these rules in more than one component. So Ravi puts them in one helper file, tea-kit/attribute-types.js. Booleans need no helper, because hasAttribute() is the whole rule:
export function toKeyword(text, keywords, missing, invalid = missing) {
if (text === null) return missing;
const lower = text.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
return keywords.includes(lower) ? lower : invalid;
}
export function parseInteger(text) {
const match = /^[\t\n\f\r ]*([+-]?\d+)/.exec(text);
return match === null ? null : Number(match[1]);
}
export function toInteger(text, fallback, min = -2147483648) {
const value = text === null ? null : parseInteger(text);
return value !== null && value >= min && value <= 2147483647 ? value : fallback;
}
export function toNonNegativeInteger(text, fallback) {
return toInteger(text, fallback, 0);
}
export function parseFloatingPoint(text) {
const match = /^[\t\n\f\r ]*([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/.exec(text);
const value = match === null ? NaN : Number(match[1]);
return Number.isFinite(value) ? value : null;
}
export function toFloat(text, fallback) {
const value = text === null ? null : parseFloatingPoint(text);
return value ?? fallback;
}
export function toJson(text, fallback) {
if (text === null) return fallback;
try {
return JSON.parse(text);
} catch {
return fallback;
}
}- Lines 1 to 5 are
toKeyword(). Line 3 lowercases only the letters A to Z. Line 4 gives the keyword, or the invalid value default. - Lines 7 to 10 are
parseInteger(), the integer rules from the sugar cup. - Lines 12 to 15 are
toInteger(). It checks the number against a minimum and a maximum, 2147483647. That's the biggest number the built-in whole-number properties accept. Anything else gives the fallback. - Lines 17 to 19 are
toNonNegativeInteger():toInteger()with a minimum of 0. - Lines 21 to 30 do the same for decimals. Line 22's pattern adds a decimal point and an exponent.
- Lines 32 to 39 are
toJson(). It gives the fallback for missing or broken JSON.
Why only A to Z on line 3? toLowerCase() also changes a few letters outside that range. The Kelvin sign, a K used in science, becomes a plain k. So picture checkbox typed with a Kelvin sign in place of its k. Chrome gives text for that type, not checkbox, and so does line 3. For the cup's three sizes, toLowerCase() gives the same answers.
The course checked these functions against Chrome's own elements, with dozens of texts each. For keywords, it compared input.type, dir, and crossOrigin. For numbers, it compared a list item's value, start, maxLength, cols, tabIndex, and a meter's min. They agree every time.
CSS can't see the default
One reader never calls your getter: CSS. A selector like tea-cup[size="large"] compares the attribute's text exactly. It misses LARGE, and it can't match a default that isn't written. Burton Smith's advice: give every cup the default style with no attribute selector, and add the other sizes on top. The i flag makes a selector ignore case:
<style> tea-cup { display: block; font-size: 1em; } tea-cup[size="large" i] { font-size: 1.5em; } tea-cup[size="small" i] { font-size: 0.75em; }</style> <tea-cup size="LARGE">Large</tea-cup><tea-cup size="huge">Huge</tea-cup><tea-cup>No size</tea-cup>- Line 2 gives every cup the medium style.
- Line 3 makes large cups bigger. The
ibefore]makes it matchLARGEtoo. - Lines 7 to 9 are three cups.
In the result, Large has a 24-pixel font, and Huge and No size both have 16. The cup with a bad size looks like a medium cup, which is just what its getter says. Built-in attributes like type already match in any case. The HTML Standard keeps a list of them.
Adding typed attributes to the tea kit
Back to Ravi. He adds the helper file to the kit and uses it in two components. The label's minutes becomes a whole number, 0 or more, with a default of 3. The label also gets a boolean sold-out. The timer's seconds becomes a property, with a default of 60. Here is a page with a bad time, a sold-out tea, and a negative timer:
<p><tea-label name="Green tea" minutes="4 min"></tea-label></p><p><tea-label name="Oolong" minutes="3" sold-out></tea-label></p><p><tea-timer seconds="-30"></tea-timer></p> <script type="module"> await import("./tea-kit/index.js"); const [green, oolong] = document.querySelectorAll("tea-label"); console.log(green.textContent); console.log(oolong.textContent); console.log(document.querySelector("tea-timer").textContent); oolong.soldOut = false; console.log(oolong.textContent);</script>- Line 1's label has
minutes="4 min". Line 8 printsGreen tea: brew for 4 minutes. - Line 2's label has
sold-out. Line 9 printsOolong: sold out. - Line 3's timer has
seconds="-30". Line 10 prints60 s. A negative time gets the default. - Line 11 sets
soldOuttofalse. Line 12 printsOolong: brew for 3 minutes.
With lesson 5.1's kit, the same page printed Green tea: brew for NaN minutes. It ignored sold-out, and its timer showed -30 s.
Open the tea-kit/tea-label.js tab:
- Line 15 is the
minutesgetter. It usestoNonNegativeInteger()with a default of 3. - Lines 22 to 28 are
soldOut:hasAttribute()andtoggleAttribute(), as on the iced cup. - Line 31 adds
soldOutto the upgrade-property pattern from lesson 4.2. - Line 48 shows "sold out" in place of the brewing time.
In the tea-kit/tea-timer.js tab, line 7 is the seconds getter, with a default of 60. Lines 10 to 12 are its setter. Line 15 runs the upgrade-property pattern, and line 18 starts the countdown from this.seconds.
Why it matters: Asha can write the kit's attributes the way she writes HTML. And a typo shows a sensible default, not NaN.
Common mix-ups
- "disabled="false" turns the button back on." No. Any text means on. Remove the attribute, or set
button.disabled = false. - "setAttribute("iced", false) removes the attribute." No. It writes the text
false, and the attribute still means on. UsetoggleAttribute("iced", false)orremoveAttribute("iced"). - "draggable="false" is still on, like disabled="false"." No.
draggableis an enumerated attribute, andfalseis one of its keywords. It really turns dragging off. - "Keywords have to match exactly, capitals and all." No. Keywords ignore the case of A to Z, so
type="EMAIL"makes an email box. CSS selectors on your own attributes do care about case, unless you add theiflag. - "The property gives back whatever text the page wrote." No. A built-in property gives a keyword or a default.
getAttribute()gives the text. - "Number() reads attribute numbers the way HTML does." No.
Number("5px")isNaN, andNumber("")is 0. HTML gives 5, and the default. - "A getter should throw on bad text, so developers notice." No. Built-in getters never throw. They give a default, and so does Lit's converter.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
What do lines 3 and 5 print?
const details = document.createElement("details");
details.setAttribute("open", "false");
console.log(details.open);
details.open = false;
console.log(details.hasAttribute("open"));true, then false. Line 2 writes the text false, but the attribute is there, so the element is open. Line 4 sets the property to false, which removes the attribute.
What do lines 3 and 5 print?
const input = document.createElement("input");
input.setAttribute("type", "Email");
console.log(input.type);
input.setAttribute("type", "e-mail");
console.log(input.type, input.getAttribute("type"));email, then text e-mail. Email matches the keyword email, because case doesn't matter. e-mail isn't a keyword, so the property gives the default, text, while getAttribute() gives the text as written.
What does line 5 print?
const list = document.createElement("ol");
list.setAttribute("start", "3rd");
const first = list.start;
list.setAttribute("start", "three");
console.log(first, list.start);3 1. 3rd starts with the digit 3, and the rules ignore rd. three has no digits at the start, so start gives its default, 1.
Line 15 sets iced to false, but line 16 prints true. Fix the setter. What does line 16 print then?
<tea-cup iced>Green tea</tea-cup> <script> class TeaCup extends HTMLElement { get iced() { return this.hasAttribute("iced"); } set iced(value) { this.setAttribute("iced", value); } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); cup.iced = false; console.log(cup.iced);</script><tea-cup iced>Green tea</tea-cup> <script> class TeaCup extends HTMLElement { get iced() { return this.hasAttribute("iced"); } set iced(value) { this.toggleAttribute("iced", Boolean(value)); } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); cup.iced = false; console.log(cup.iced);</script>The old setter wrote the text "false", and the getter saw an attribute, so the cup stayed iced. With toggleAttribute(), false removes the attribute, and line 16 prints false.
The getter on line 8 gives back the text as it is, so line 14 prints LARGE huge null. Make size an enumerated attribute: small, medium, or large, in any case, with medium for anything missing or unknown. What does the last line print then?
<tea-cup size="LARGE"></tea-cup><tea-cup size="huge"></tea-cup><tea-cup></tea-cup> <script> class TeaCup extends HTMLElement { get size() { return this.getAttribute("size"); } } customElements.define("tea-cup", TeaCup); const cups = [...document.querySelectorAll("tea-cup")]; console.log(...cups.map((cup) => cup.size));</script><tea-cup size="LARGE"></tea-cup><tea-cup size="huge"></tea-cup><tea-cup></tea-cup> <script> class TeaCup extends HTMLElement { get size() { const text = this.getAttribute("size"); if (text === null) return "medium"; const keyword = text.toLowerCase(); return ["small", "medium", "large"].includes(keyword) ? keyword : "medium"; } } customElements.define("tea-cup", TeaCup); const cups = [...document.querySelectorAll("tea-cup")]; console.log(...cups.map((cup) => cup.size));</script>large medium medium. LARGE lowercases to the keyword large. huge isn't a keyword, so it gets the invalid value default. The third cup has no attribute, so it gets the missing value default. Both defaults are medium.
The kit's timer writes any value into seconds. Line 5 sets -5, so line 6 prints Saved -5 60. Make the setter in the tea-kit/tea-timer.js tab throw an IndexSizeError, like maxLength. What does the page print then?
<script type="module"> await import("./tea-kit/index.js"); const timer = document.createElement("tea-timer"); try { timer.seconds = -5; console.log("Saved", timer.getAttribute("seconds"), timer.seconds); } catch (error) { console.log(error.name); }</script>import { toNonNegativeInteger } from "./attribute-types.js"; export class TeaTimer extends HTMLElement { #controller = null; get seconds() { return toNonNegativeInteger(this.getAttribute("seconds"), 60); } set seconds(value) { if (value < 0) throw new DOMException("seconds can't be negative", "IndexSizeError"); this.setAttribute("seconds", value); } connectedCallback() { this.#upgradeProperty("seconds"); if (this.#controller) return; this.#controller = new AbortController(); let left = this.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() {} #upgradeProperty(name) { if (!Object.hasOwn(this, name)) return; const value = this[name]; delete this[name]; this[name] = value; }} customElements.define("tea-timer", TeaTimer);IndexSizeError. Line 11 of the timer's file throws before the attribute is written, the way maxLength refuses -5. The getter still gives 60 for any negative text a page writes in HTML.
Check your understanding
For each question, ask which kind of attribute it is, and what the browser does with missing or bad text.
Question 1 of 7What does line 10 print for a cup written with
iced="false"?Read the code, then predict<tea-cup iced="false"></tea-cup> <script> class TeaCup extends HTMLElement { get iced() { return this.hasAttribute("iced"); } } customElements.define("tea-cup", TeaCup); console.log(document.querySelector("tea-cup").iced); </script>Choose an answer to see the explanation.
Question 2 of 7Which line turns a cup's boolean
icedattribute off?Choose an answer to see the explanation.
Question 3 of 7What does
input.typegive for<input type="NUMBER">?Choose an answer to see the explanation.
Question 4 of 7A paragraph has
dir="sideways", which isn't a keyword. What doesp.dirgive?Choose an answer to see the explanation.
Question 5 of 7What does this list item code print?
Read the code, then predictconst item = document.createElement("li"); item.setAttribute("value", "12 cups"); console.log(item.value, Number(item.getAttribute("value")));Choose an answer to see the explanation.
Question 6 of 7What happens when code runs
input.maxLength = -1?Choose an answer to see the explanation.
Question 7 of 7A component reads a JSON attribute, and the page has a typo in it. What should the getter give back?
Choose an answer to see the explanation.
Key takeaways
- A boolean attribute is on whenever it's there, whatever its text. Only removing it turns it off.
- Read a boolean with
hasAttribute(). Write it withtoggleAttribute(name, Boolean(value)), never with the text "false". - Name boolean attributes so they start out off, like
disabledandsold-out. - An enumerated attribute matches its keywords in any case, with a missing value default and an invalid value default.
- HTML reads numbers by skipping spaces, reading digits, and ignoring the rest. No digits means the default.
- Limits like "non-negative" give the default for numbers out of range. A setter may refuse them, like
maxLength. - Parse JSON once, catch errors, and fall back. A property is still better for rich data.
- A getter never throws, and never rewrites the attribute. CSS sees only the text, so style the default without a selector.
Remember the one-liner.
Read attributes the way built-in elements do: there or not for booleans, a keyword or a default for enums, HTML's digits or a default for numbers, and never a throw.
Sources
The facts on this page come from these standards, docs, and posts:
- HTML Standard: Common microsyntaxes, WHATWG.
- HTML Standard: Reflecting content attributes in IDL attributes, WHATWG.
- HTML Standard: The hidden attribute, WHATWG.
- HTML Standard: Case-sensitivity of selectors, WHATWG.
- Attribute reflection, MDN.
- Element: toggleAttribute() method, MDN.
- parseInt(), MDN.
- Modern Web Guidance: Custom Elements, Chrome for Developers.
- Lit: Reactive properties, Lit.
- reactive-element.ts at lit@3.3.3, the default converter, Lit.
- HTML attributes vs DOM properties, Jake Archibald.
- Bulletproof Web Component APIs, Burton Smith.
- Don't Rely on Default Attribute Values For Styling Web Components, Burton Smith.
Coming next: Dispatching events. Tell the outside world what happened, with events named and shaped like built-in ones.