completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Write boolean attributes that act like disabledRead them with hasAttribute(), write them with toggleAttribute(), and never turn one off with the text "false".
  • 02
    Give enumerated attributes their defaultsMatch a few keywords in any case, and fall back to a missing value default and an invalid value default.
  • 03
    Read 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:

A button written with disabled="false"Pop out in the code editor (opens in a new tab)HTML
<button disabled="false">Order green tea</button> <script>  const button = document.querySelector("button");  console.log(button.disabled);  console.log(button.getAttribute("disabled"));</script>
ResultLoading…
  • 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.

Three buttons and what the browser sees. <button> gives disabled: false. <button disabled> gives disabled: true. <button disabled="false"> gives disabled: true. Only the missing attribute means off.what the page writeswhat the browser sees<button>disabled: false<button disabled>disabled: true<button disabled="false">disabled: true
The browser only asks whether disabled is there. The text false never gets read, so the third button is disabled too.
Real-life analogyA sold-out sticker on the menu

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
The main idea

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:

Any text turns a boolean attribute onPop out in the code editor (opens in a new tab)JavaScript
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 print true: "", "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:

A boolean property writes and removes its attributePop out in the code editor (opens in a new tab)JavaScript
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 open to true. 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():

A cup with a boolean iced attributePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1 writes a cup with iced and no text.
  • Lines 5 to 7 are the getter, the function that runs when code reads cup.iced. hasAttribute() gives true when the attribute is there.
  • Lines 8 to 10 are the setter. toggleAttribute(name, force) adds the attribute when force is true, and removes it when force is false.
  • Line 15 prints true.
  • Line 16 sets iced to false. Line 17 prints false <tea-cup>Green tea</tea-cup>. The attribute is gone.
  • Line 18 sets it to "no". Line 19 prints true <tea-cup iced="">Green tea</tea-cup>, just like details.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:

setAttribute() with false writes the text falsePop out in the code editor (opens in a new tab)JavaScript
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:

Playground: the same text on a button and a cup
A button and a cup with the same attribute textPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Both are off

There's no attribute, so the button works and the cup is hot. Leaving the attribute out is the only way to say off.

Lines 1 and 2 change with your choice. The tea-cup.js tab holds the cup's class: hasAttribute() reads iced, and toggleAttribute() writes it.

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.

An input's type, in capitals, misspelled, and missingPop out in the code editor (opens in a new tab)JavaScript
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 email and "EMAIL" gives email. Keywords ignore case.
  • Then it prints "e-mail" gives text. e-mail isn't a keyword, so the input falls back to text.
  • 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.
Real-life analogyOrdering a cup size the café doesn't sell

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, and large
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:

Four built-in enumerated attributes and their defaults
AttributeWhen it's missingWhen the word is unknownWhen it's empty
<input type>, read with input.type"text""text""text"
dir, read with p.dir""""""
crossorigin, read with img.crossOriginnull"anonymous""anonymous"
popover, read with div.popovernull"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:

An input's type setter writes any textPop out in the code editor (opens in a new tab)JavaScript
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:

A cup with three sizes and a defaultPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 LARGE becomes large.
  • 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.

Three tea cups through the size getter. size="LARGE" gives "large", the a keyword, in any case. size="huge" gives "medium", the invalid value default. no size gives "medium", the missing value default.size="LARGE""large"a keyword, in any casesize="huge""medium"invalid value defaultno size"medium"missing value defaultget size()
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:

Playground: one size attribute, three readers
Write the size, then read itJavaScript
cup.setAttribute("size", "LARGE");
console.log(cup.size);
Three readers of the same text

cup.size gives "large"

An input with this type gives "text"

tea-cup[size="large"] doesn't match

Try it yourself
cup.size is "large"

Keywords ignore the case of A to Z, so this reads as large. CSS doesn't: tea-cup[size="large"] needs the exact text.

The getter is the one from the sizes example: three keywords, any case, and medium for anything else. The playground runs the same rule on your text, in this page.

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:

Boolean or enumerated?
  • A button's disabled
  • A details element's open
  • A checkbox's checked
  • An input's type
  • The dir attribute
  • The popover attribute
  • The draggable attribute
  • The contenteditable attribute
Try it yourself
0 of 8 correct

Sort each attribute by how the browser reads it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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:

An ordered list's start, from six textsPop out in the code editor (opens in a new tab)JavaScript
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 3 and " 3" gives 3. Spaces at the start are skipped.
  • Then "3rd" gives 3 and "3.9" gives 3. Reading stops at the first character that isn't a digit.
  • Then "three" gives 1 and "" gives 1. No digits at the start means no number. So the list uses its default, 1.

The rules are short. In plain words:

  1. Skip any spaces, tabs, and line breaks at the start.
  2. Read a minus sign if there is one. A plus sign is skipped.
  3. If the next character isn't a digit, 0 to 9, there's no number.
  4. Read the digits. Stop at the first character that isn't one, and ignore the rest.
Reading the text " 5px" with HTML's rules for parsing integers, one character at a time. space: skip, space: skip, 5: read, p: stop, x: ignored. The result is the number 5.the attribute's textspaceskipspaceskip5readpstopxignored5the number
The rules skip spaces, read the digits, and stop at the first character that isn't a digit. So " 5px" and "5 minutes" both give 5.
Real-life analogyReading the number at the start of an order note

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:

One text, three ways to read it
What the attribute saysNumber(text) givesparseInt(text, 10) givesHTML's rules give
"5"555
" 5"555
"5px"NaN55
"5.9"5.955
""0NaNNo number, so the default
"five"NaNNaNNo number, so the default
"0x10"1600
"1e3"100011

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:

maxLength refuses a negative numberPop out in the code editor (opens in a new tab)JavaScript
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, maxLength gives the standard's default for these properties, -1.
  • Line 3 writes -5 into the attribute. Line 4 prints -1 again. 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:

A progress bar's max, from six textsPop out in the code editor (opens in a new tab)JavaScript
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.5 and "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:

A cup with a sugar attribute read by HTML's rulesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 null when 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:

Playground: five ways to read a number
Write the sugar, then read itJavaScript
cup.setAttribute("sugar", "2 spoons");
console.log(cup.sugar);
What each one gives

HTML's integer rules: 2

Number(text): NaN

parseInt(text, 10): 2

The cup's sugar, default 0: 2

HTML's decimal rules: 2

Try it yourself
The cup's sugar is 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.

HTML's rules are the ones built-in elements use, like an ordered list's start. The cup's sugar uses them too, with 0 for anything missing, bad, or negative.

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:

A menu that parses its JSON once, and survives a typoPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 has a typo. Mint tea has 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, the catch block warns in the console, and teas stays an empty list.
  • Line 18 keeps the result only if it's an array. Text like 5 is 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.

A getter reading a bad value. The HTML holds size="huge", which stays as written. An arrow leads to get size(), and from there to two cards: "medium", the default, which it returns, and a crossed-out card, throw an error, which it never does.HTMLsize="huge"stays as writtenget size()"medium"the defaultthrow an errornever
The getter turns bad text into the default and never throws. It doesn't change the attribute either: the page wrote huge, and the HTML keeps it.
Real-life analogyA smudged order slip

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:

What each kind of attribute gives for missing and bad text
Kind of attributeWhen it's missingWhen the text is badRead it with
Boolean, like icedIt's off.There's no bad text. Any text means on.hasAttribute()
Enumerated, like sizeThe missing value default.The invalid value default.toKeyword()
Whole number, like startThe default.The default. Text after the digits is ignored.toInteger()
Whole number, 0 or more, like sugarThe default.The default, and for a negative number too.toNonNegativeInteger()
Decimal, like maxThe default.The default. Text after the number is ignored.toFloat()
JSON, like teasThe 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:

tea-kit/attribute-types.js, the rules as functionsJavaScript
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:

Styling sizes in any case, with the default as the basePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 gives every cup the medium style.
  • Line 3 makes large cups bigger. The i before ] makes it match LARGE too.
  • 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:

Three kit components with bad and boolean attributesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1's label has minutes="4 min". Line 8 prints Green tea: brew for 4 minutes.
  • Line 2's label has sold-out. Line 9 prints Oolong: sold out.
  • Line 3's timer has seconds="-30". Line 10 prints 60 s. A negative time gets the default.
  • Line 11 sets soldOut to false. Line 12 prints Oolong: 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 minutes getter. It uses toNonNegativeInteger() with a default of 3.
  • Lines 22 to 28 are soldOut: hasAttribute() and toggleAttribute(), as on the iced cup.
  • Line 31 adds soldOut to 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. Use toggleAttribute("iced", false) or removeAttribute("iced").
  • "draggable="false" is still on, like disabled="false"." No. draggable is an enumerated attribute, and false is 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 the i flag.
  • "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") is NaN, and Number("") 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.

Exercise 1 · Warm-upA details element that says false

What do lines 3 and 5 print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const details = document.createElement("details");
details.setAttribute("open", "false");
console.log(details.open);
details.open = false;
console.log(details.hasAttribute("open"));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upEmail in capitals

    What do lines 3 and 5 print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    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"));

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeThird, or three

      What does line 5 print?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const list = document.createElement("ol");
      list.setAttribute("start", "3rd");
      const first = list.start;
      list.setAttribute("start", "three");
      console.log(first, list.start);

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeA cup that stays iced

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeThree sizes and two defaults

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeA timer that refuses negatives

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask which kind of attribute it is, and what the browser does with missing or bad text.

              The attribute types quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does line 10 print for a cup written with iced="false"?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              2. Question 2 of 7Which line turns a cup's boolean iced attribute off?

                Choose an answer to see the explanation.

              3. Question 3 of 7What does input.type give for <input type="NUMBER">?

                Choose an answer to see the explanation.

              4. Question 4 of 7A paragraph has dir="sideways", which isn't a keyword. What does p.dir give?

                Choose an answer to see the explanation.

              5. Question 5 of 7What does this list item code print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const item = document.createElement("li");
                item.setAttribute("value", "12 cups");
                console.log(item.value, Number(item.getAttribute("value")));

                Choose an answer to see the explanation.

              6. Question 6 of 7What happens when code runs input.maxLength = -1?

                Choose an answer to see the explanation.

              7. 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 with toggleAttribute(name, Boolean(value)), never with the text "false".
              • Name boolean attributes so they start out off, like disabled and sold-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:

              Coming next: Dispatching events. Tell the outside world what happened, with events named and shaped like built-in ones.

              CompleteFrontend Clear concepts. Working examples.