HTML web components
HTML web components wrap HTML that already works in a custom element and add behavior with JavaScript. Build a tea filter that works without the script.
- 01Wrap HTML that already worksPut a custom element around a list, a form, or a button, and add behavior to the elements inside it.
- 02Build in layersStart with HTML that works, style both states with CSS, and hide only the parts that need the script.
- 03Choose the right kind of componentTell an HTML web component from a JavaScript web component, and know when shadow DOM is worth adding.
What is an HTML web component?
Leaf and Kettle's tea page comes from the shop's server as plain HTML. It's a list of teas. Ravi wants to add a search box. As you type, the list should shrink to the teas that match.
Asha has one worry. Some customers read the menu on a train, on a slow phone. Their script may come late, or never. Will they still see the teas?
Yes, if Ravi builds an HTML web component. An HTML web component is a custom element that wraps HTML that already works, and adds behavior with JavaScript. Before the script runs, or if it never does, the reader still gets the HTML.
Jeremy Keith gave the pattern its name in his post HTML web components. His test is short. An empty custom element isn't one. A custom element around HTML that's already there is. Lesson 1.3 met the idea briefly, in Should a web component use shadow DOM or light DOM?. Here is Ravi's:
<tea-filter> <label>Search teas <input type="search"></label> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter> <script src="tea-filter.js"></script>- Line 1 opens the custom tag,
<tea-filter>. - Line 2 is a label with a search box inside it.
type="search"is a text box made for searching. - Lines 3 to 8 are a plain list of four teas.
- Line 11 loads the class from
tea-filter.js. Click the second tab to see it.
In the tea-filter.js tab:
- Line 3 finds the box inside the tag. Line 4 finds the four teas.
- Line 5 runs some code each time the text in the box changes. The browser tells the box with an
inputevent. - Line 6 reads the words in the box, in lowercase.
- Lines 7 and 8 go through the teas. A tea whose name doesn't hold the words gets the
hiddenattribute. That attribute tells the browser not to show the element. - Line 14 registers the class for the tag
tea-filter.
Type mint in the result. Only Mint tea stays. Clear the box, and all four come back.
tea-filter.js runs, typing mint hides the three teas that don't match.A good teapot pours on its own. A clip-on strainer makes it better: it catches the leaves. If the strainer gets lost, you still get your tea. You just get a few leaves too.
- In real life: The teapot that pours on its own
- In JavaScript: The HTML list of teas
- In real life: The strainer clipped to the spout
- In JavaScript: The
tea-filterclass - In real life: Catching the leaves as you pour
- In JavaScript: Hiding the teas that don't match
- In real life: Pouring with the strainer lost
- In JavaScript: Reading the list when the script never loads
An HTML web component wraps HTML that already works, and adds behavior with JavaScript. The page writes the content. The class only reads it and adds a job. If the script never loads, the reader still gets the content.
How do you wrap existing HTML in a web component?
Every HTML web component is made in the same three steps. Here they are, for the tea filter:
- Write HTML that works on its own. The teas are a real list. A reader can read it with no script at all.
- Wrap it in your tag. Until the tag is defined, the browser treats it much like a
<span>, the HTML Standard says. It shows what's inside. - In
connectedCallback(), find the parts and add behavior.this.querySelector()finds them, because they are the tag's own children.
Two rules from earlier lessons keep step 3 safe. Never read children in the constructor, as What the constructor may do explained. And load the script after the HTML, like line 11, or as a module. Then the children are there when connectedCallback() runs. The custom element lifecycle in order showed why.
Notice what the class doesn't do. It never writes the list. It reads the HTML and adds a job. Here is the other way to build the same list. The teas are data in an attribute, and the class builds everything:
<tea-list teas="Green tea, Black tea, Mint tea, Oolong"></tea-list> <script> class TeaList extends HTMLElement { connectedCallback() { const teas = this.getAttribute("teas").split(", "); this.innerHTML = `<ul>${teas.map((tea) => `<li>${tea}</li>`).join("")}</ul>`; } } customElements.define("tea-list", TeaList);</script>- Line 1 is the tag, empty. Its
teasattribute holds all four names in one string. - Line 6 splits that string at each comma and space, into a list of names.
- Line 7 builds a
<ul>from the names and puts it inside the tag.
The result looks the same. Now press Edit & run and delete lines 3 to 11, the whole script. The page goes blank. There never was a list in the HTML.
Jim Nielsen calls this kind a JavaScript web component. In his post, it's "meaningless to the end user" without its script. Eric Meyer warns against it in Blinded By the Light DOM. Put a slider's settings in attributes, he writes, and you end up rebuilding the HTML from them. He wraps a real label and a real range input instead. That way, he says, you get everything HTML gives them for free.
Why it matters: keep the content in the HTML. Give the script only the extra job.
What is progressive enhancement for web components?
Lesson 2.5 named the idea: progressive enhancement. You start with HTML that works for everyone. Then you make it better where the browser can. Custom elements fit this well. The HTML Standard says upgrades "allow progressive enhancement of the content in the custom element".
A page built this way has three layers:
- HTML holds the content and the controls that work with nothing else: text, lists, links, and forms.
- CSS styles the page, before the upgrade and after it.
- JavaScript adds behavior to what's already there.
Each layer must work without the one above it.
A building gets a new lift. It's faster, and most people use it. But nobody takes out the stairs. On the day the lift breaks, everyone still gets upstairs. It just takes a bit longer.
- In real life: The stairs
- In JavaScript: The HTML, which always works
- In real life: The lift
- In JavaScript: The script's behavior
- In real life: A broken lift
- In JavaScript: A script that never loads
- In real life: Taking the stairs out to make room
- In JavaScript: Building the content with the script only
Does the tea filter's HTML layer really work on its own? Take the script away and see. Pick a choice, then type mint in the result:
<tea-filter> <label>Search teas <input type="search"></label> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter> <script src="tea-filter.js"></script>Line 11 loads tea-filter.js. As you type, the class gives every tea that doesn't match the hidden attribute.
With the script gone, the list is fine. The box is the problem. It looks ready, and it does nothing. A reader types, waits, and gives up. The next section fixes that.
You can try this on any site. In Chrome, open DevTools and its Command Menu, type javascript, and pick Disable JavaScript. Then reload. Chrome's DevTools docs show the steps.
Why it matters: an HTML web component is only as good as its HTML layer. Test it with the script gone.
What should you hide until a web component is defined?
Hide the parts that only work with the script. Never hide the content. For the tea filter, that means hiding the box and keeping the list. Lesson 2.4 taught the tool: the :defined selector. It matches a custom element once its class has upgraded it.
<style> tea-filter:not(:defined) label { display: none; }</style> <tea-filter> <label>Search teas <input type="search"></label> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter> <script src="tea-filter.js"></script>- Line 2 picks a label inside a
tea-filterthat isn't defined yet. It hides the label, and the box inside it goes too. - Lines 5 to 13 are the same filter as before.
- Line 15 loads the script.
With the script, the box shows and the filter works. Now press Edit & run and delete line 15. The page shows the four teas and no box. There is nothing on the page that doesn't work.
tea-filter.js never loads, the reader still gets the HTML, styled by the CSS.At Leaf and Kettle, the "We take cards" sign only goes up once the card machine is switched on. If the machine is broken, there's no sign. Nobody waits at the till with a card. Cash always works, so the shop never closes.
- In real life: The "We take cards" sign
- In JavaScript: The search box
- In real life: Switching the card machine on
- In JavaScript: The script defining
tea-filter - In real life: No sign while the machine is off
- In JavaScript:
tea-filter:not(:defined) label { display: none; } - In real life: Cash, which always works
- In JavaScript: The list of teas
Why not hide the whole <tea-filter> until it's defined? Because a script that fails would hide the teas too. Lesson 2.4 called the safe way failing open: if the script never loads, the content shows anyway.
One more detail. :defined starts matching as soon as the constructor has run. connectedCallback() runs after that. If it throws, the tag still matches :defined, and the box shows with nothing behind it. The quiz has an example. For a safer switch, let the class show the control itself, once the control is ready. The show more button below works that way.
Zach Leatherman calls :defined "an incredibly useful tool for styling HTML Web Components", in his taxonomy of web components. Why it matters: a control that does nothing is worse than no control. Show each control only when it can work.
How do you keep a form working without JavaScript?
Hiding the box is safe. But a reader with no script still can't search. Can the box work with no script at all? Yes. Put it in a form. Forms send what you typed to a server, and they need no JavaScript to do it.
<tea-filter> <form action="teas"> <label>Search teas <input type="search" name="q"></label> <button>Search</button> </form> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter> <script src="tea-filter.js"></script>- Line 2 opens a form.
action="teas"is the page the form is sent to. - Line 3 gives the box a name,
q. A form sends each box's value under its name. - Line 4 is a button that sends the form. Pressing Enter in the box does the same.
The tea-filter.js tab has the same filter as before, plus three new lines:
- Line 3 finds the form.
- Line 13 runs code when the form is sent. That's the
submitevent, from the Form events lesson. - Line 14 calls
preventDefault(). It tells the browser to skip what it would do on its own, here loading a new page. The Default actions lesson covers it.
Type mint, and the list filters as before. Press Enter, and the page stays where it is. Line 14 stopped it.
Without the script, nothing stops the form. Pressing Enter sends it, the way forms always work. The browser asks the server for a new page. This playground shows what it asks for:
<form action="teas">
<label>Search teas <input type="search" name="q" value="mint"></label>
<button>Search</button>
</form>teas?q=mint
- Mint tea
The server sends back one tea: Mint tea.
For mint, the browser asks for teas?q=mint. The box's name and your words come after the question mark. The shop's server reads them and sends back a page with only Mint tea. The reader gets the same answer, one page load later.
Chris Ferdinandi met this on an app he worked on for NASA. In his post, every action was "either a link" or "a form that submits data to the server", with no JavaScript needed. His <ajax-form> wraps a form. The form submits as normal until the component runs. Then the component enhances it, for example by sending it with JavaScript and showing a message.
Links work the same way. A link that the script makes faster should still go somewhere real without the script. Why it matters: a form or a link in the HTML layer gives every reader the job, not only the ones whose script loaded.
How do you build an accessible show more button?
The menu page lists six teas. Asha wants the first three to show, with a More teas button for the rest. Without the script, all six should show.
A button that shows and hides content is called a disclosure. The ARIA Authoring Practices Guide says how to build one, so screen readers can use it. HTML's own <details> is a disclosure too, and lesson 1.3 says to use it when it fits. Here it doesn't: three teas must always show, and a closed <details> hides everything but its summary.
<tea-more> <ul id="teas"> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> <li>Chai</li> <li>Sencha</li> </ul> <button aria-controls="teas" hidden>More teas</button></tea-more> <script src="tea-more.js"></script>- Lines 2 to 9 list six teas. The list's
idisteas. - Line 10 is a real
<button>.aria-controls="teas"names the list it controls.hiddenkeeps it off the page until the script is ready.
In the tea-more.js tab:
- Line 4 picks every tea after the third one.
- Lines 5 to 8 make one function that opens or closes. Line 6 sets
aria-expandedtotrueorfalse. Line 7 shows or hides the extra teas. - Line 9 closes it.
- Line 10 shows the button, only now, when it can work.
- Lines 11 to 13 flip between open and closed on each click.
Click More teas, and Oolong, Chai, and Sencha appear. Or press Tab to reach the button, then Enter or Space. A real <button> gives you the keyboard for free.
Screen readers read the accessibility tree: the browser's list of what each thing on the page is. Here is Chrome's tree for this page:
Before a click, the tree marks the button as not expanded, and a screen reader calls it collapsed. After a click, it calls it expanded. That's what aria-expanded is for: it says whether the content the button controls is showing. Without the script, the button stays hidden, so it isn't in the tree at all. The list has all six teas.
A meeting room door has a small sign. It says which room this is, and a slider shows Open or Closed. You know what you will find before you push the door. Someone who can't see inside learns it from the sign.
- In real life: The door you push
- In JavaScript: The
<button> - In real life: Room 3, printed on the sign
- In JavaScript:
aria-controls="teas" - In real life: The slider that says Open or Closed
- In JavaScript:
aria-expanded - In real life: The room behind the door
- In JavaScript: The extra teas
Chris Ferdinandi's show-hide component works the same way. Its button starts with hidden. The script removes it and sets aria-expanded. The tea filter could do more for screen readers, too, like saying how many teas match. That's a job for a live region, in Accessible components.
Why it matters: build controls from real elements, and keep their state in ARIA attributes, so every reader gets it.
Do web components need shadow DOM?
No. Not one component in this lesson has a shadow root. MDN's Using custom elements describes a custom element as a class that extends HTMLElement. In its constructor, MDN says, you can "perhaps create a shadow root". Perhaps: it's a choice.
Without one, the component's markup is the page's markup. Lesson 5.5 called this the light DOM. Here is what you get:
- The page's CSS styles the teas and the box, like any other HTML.
- Page scripts find real elements.
document.querySelectorAll("tea-filter li")finds all four teas. - Find in page finds Mint tea, because it's page text.
- Screen readers get the real list and the real button, as the tree above showed.
- A server sends it as plain HTML. It needs nothing more, as lesson 2.5 showed.
The page's CSS reaches everything, for worse too. Say the page has li { display: flex; }. That rule beats the browser's own rule for hidden, so the filter's hidden teas still show. One page rule wins it back: [hidden] { display: none !important; }.
So when does a component need shadow DOM? When it draws parts of its own, which must look the same on any page. A date picker in a design system is one. Or when it needs slots, to put the page's content inside its own layout. Hawk Ticehurst lists what you give up without it, in A year working with HTML Web Components:
- You repeat the component's markup each time you use it.
- Its styles aren't kept apart from the page's.
- It has no slots.
Jeremy Keith calls shadow DOM "a last resort". Simon MacDonald of Enhance says it "should be reached for only when needed", in Shadow DOM: Not by Default. Lesson 1.3's light DOM or shadow DOM table compares the two, and Shadow DOM, templates, and slots builds shadow roots in full.
When should you use HTML web components?
One question sorts them: is there HTML that works without the script?
An HTML web component fits best:
- on content pages, like a blog or a shop's menu, where the HTML is the point;
- on pages that a server or a site builder makes. Astro's docs build an
<astro-heart>this way: a button and a count in the HTML, and a class that adds clicks; - for small behaviors on markup: filtering a list, showing more, or a readout for a slider;
- around forms that already send to a server.
Chrome's Web Components guide says the same. For "lots of markup, a little interactivity", keep the markup in the light DOM and let a small custom element add to it. GitHub's team described their elements as "progressively enhanced with JavaScript". Their first ones shipped in 2014.
It fits poorly in two places:
- App-like widgets that draw everything from data, like a chart of this week's sales. There is no HTML to show first.
- Screens inside a React or Vue app. Chrome's guide says to use the framework's own components there.
Even Zach Leatherman builds some JavaScript web components. He lists his <speedlify-score> as "entirely JS generated content", with "no fallback". Each kind has its place.
Several people wrote about this pattern. Each post is worth reading:
- Jeremy Keith named it, and asks for augmentation, not replacement: add to the HTML instead of rebuilding it.
- Jim Nielsen points out that these components show before JavaScript, and React components can't. His example wraps an
<img>in a<user-avatar>. - Eric Meyer wraps a label and a range input, then styles it all with the page's own CSS.
- Zach Leatherman sorts his own components into HTML and JavaScript ones.
- Chris Ferdinandi wraps forms that already work.
- Hawk Ticehurst lists the limits, after a year of building them.
Read each row across: a question, then the answer for each kind.
| Question | HTML web component | JavaScript web component |
|---|---|---|
| What is inside the tag? | Working HTML, like a list, a form, or an image. | Nothing, or data in its attributes. |
| What does the reader get before the script runs? | The HTML inside, ready to read and use. | An empty spot on the page. |
| What does the script do? | It adds behavior to the HTML that is already there. | It builds everything from data. |
| What styles it? | The page's own CSS, like any other HTML. | Often its own CSS, kept apart in a shadow root. |
| Where does it fit best? | Content pages, server-rendered pages, and small behaviors. | App-like widgets drawn from data, like a chart. |
Now sort some real components. Ask what the reader sees if the script never loads:
<tea-filter>around a search box and a list of teas<tea-list teas="Green tea, Mint tea">with nothing inside- Jim Nielsen's
<user-avatar>around an<img> <user-avatar src="…" name="…">with nothing inside- Eric Meyer's
<super-slider>around a<label>and a range input - Chris Ferdinandi's
<ajax-form>around a<form> - Zach Leatherman's
<speedlify-score>, with every number drawn by its script - A
<tea-chart>that draws this week's sales from JSON numbers
Sort each component by what's inside its tag in the HTML.
Adding a tea filter to the tea kit
The tea kit gets its first HTML web component: tea-kit/tea-filter.js. It's the form version, ready to use on any page:
<tea-filter> <form action="teas"> <label>Search teas <input type="search" name="q"></label> <button>Search</button> </form> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter> <script type="module"> import "./tea-kit/index.js";</script>- Lines 1 to 12 are the same form and list as before.
- Line 15 loads the whole kit, which now defines
tea-filter.
Type tea, and Oolong hides. Press Enter, and the page stays. Now open the tea-kit/tea-filter.js tab:
- Lines 1 to 5 describe the tag for tools, as Designing a component API showed.
- Lines 9 to 13 listen on the tag itself. The box's
inputevents and the form'ssubmitevents bubble up to it. The constructor adds them once, so moving the tag can't add a second listener, a problem lesson 3.3 showed. - Line 11 stops the form from loading a new page.
- Line 17 filters once when the tag joins the page. A box that already holds words starts out right.
- Line 21 finds the box, and line 24 finds the teas, each time. Teas added later get filtered too.
- Line 22 stops early when there is no search box.
- Line 23 trims spaces from both ends, so a stray space before
mintstill finds Mint tea.
The kit's custom-elements.json lists the new tag too. Nothing in the file attaches a shadow root.
Common mix-ups
- "Web components need shadow DOM." No. A custom element is a class. A shadow root is a separate choice, and none of this lesson's components has one.
- "An HTML web component works without JavaScript." No. Its HTML works without JavaScript. Its behavior still needs the script.
- "Hide the whole component until it's defined." No. Hide only the controls that need the script. A failed script would hide your content too.
- "
:definedmeans my setup worked." No. It means the upgrade ran.connectedCallback()can still throw after that. - "An empty tag with its data in attributes is an HTML web component." No. With nothing inside, the reader sees nothing until the script runs. That's a JavaScript web component.
- "Showing and hiding the teas is enough for screen readers." No. A screen reader also needs
aria-expandedon a real button, to say whether the content is showing. - "A form inside a component can't work without the script." No. A form in the HTML sends itself to the server. The script only adds a faster way.
Practice exercises
Answer first, then use the hints. The results run live, so you can check yourself.
This is the overview page with its script line gone. How many teas does the page show?
<tea-filter>
<label>Search teas <input type="search"></label>
<ul>
<li>Green tea</li>
<li>Black tea</li>
<li>Mint tea</li>
<li>Oolong</li>
</ul>
</tea-filter><tea-filter> <label>Search teas <input type="search"></label> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter>Four. The list is plain HTML, so every tea shows. The box shows too, and typing in it does nothing.
Type MINT, in capitals, into the box. Which tea stays?
<tea-filter> <label>Search teas <input type="search"></label> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter> <script src="tea-filter.js"></script>Mint tea. Line 6 lowercases your words to mint, and line 8 lowercases each name, so capitals don't matter.
This page's script never loads. Write a rule on line 2 that hides the label until tea-filter is defined. Fill in the blank: tea-filter____ label.
<style> /* Hide the label until tea-filter is defined. */</style> <tea-filter> <label>Search teas <input type="search"></label> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter><style> tea-filter:not(:defined) label { display: none; }</style> <tea-filter> <label>Search teas <input type="search"></label> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul></tea-filter>tea-filter:not(:defined) label { display: none; }. The page has no script, so tea-filter is never defined. The label and its box hide, and the four teas stay.
Here the script failed, and a More teas button shows but does nothing. Which attribute is missing from line 10?
<tea-more> <ul id="teas"> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> <li>Chai</li> <li>Sencha</li> </ul> <button aria-controls="teas">More teas</button></tea-more><tea-more> <ul id="teas"> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> <li>Chai</li> <li>Sencha</li> </ul> <button aria-controls="teas" hidden>More teas</button></tea-more>hidden. With it, the button stays off the page until a script removes it. Without a script, the reader sees six teas and no dead button.
This show more button hides and shows the teas, but never says which. Add aria-expanded on line 19. After one click, what is its value?
<tea-more> <ul id="teas"> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> <li>Chai</li> </ul> <button aria-controls="teas" hidden>More teas</button></tea-more> <script> class TeaMore extends HTMLElement { connectedCallback() { const button = this.querySelector("button"); const extras = [...this.querySelectorAll("li")].slice(3); let open = false; const show = () => { // Tell screen readers whether the extra teas are showing. for (const tea of extras) tea.hidden = !open; }; show(); button.hidden = false; button.addEventListener("click", () => { open = !open; show(); }); } } customElements.define("tea-more", TeaMore);</script><tea-more> <ul id="teas"> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> <li>Chai</li> </ul> <button aria-controls="teas" hidden>More teas</button></tea-more> <script> class TeaMore extends HTMLElement { connectedCallback() { const button = this.querySelector("button"); const extras = [...this.querySelectorAll("li")].slice(3); let open = false; const show = () => { button.setAttribute("aria-expanded", open); for (const tea of extras) tea.hidden = !open; }; show(); button.hidden = false; button.addEventListener("click", () => { open = !open; show(); }); } } customElements.define("tea-more", TeaMore);</script>true. show() runs once at the start, so the attribute begins as false. The first click flips open and runs show() again, so it becomes true.
Eric Meyer's super-slider adds a readout next to a real slider. Do the same: show the slider's value as 3 of 5, and keep it right as it moves. What does the readout say before you move the slider?
<tea-strength> <label>Strength <input type="range" min="1" max="5" value="3"></label></tea-strength> <script> class TeaStrength extends HTMLElement { connectedCallback() { // Put a span after the label that says "3 of 5", // and keep it right when the slider moves. } } customElements.define("tea-strength", TeaStrength);</script><tea-strength> <label>Strength <input type="range" min="1" max="5" value="3"></label></tea-strength> <script> class TeaStrength extends HTMLElement { connectedCallback() { const slider = this.querySelector("input"); const readout = document.createElement("span"); const update = () => (readout.textContent = ` ${slider.value} of ${slider.max}`); update(); this.querySelector("label").after(readout); slider.addEventListener("input", update); } } customElements.define("tea-strength", TeaStrength);</script>3 of 5. The slider starts at its value, 3, and its max is 5. Without the script, the reader still has a working slider.
Check your understanding
For each question, ask what the reader gets with the script, and what they get without it.
Question 1 of 8Which of these is an HTML web component?
Choose an answer to see the explanation.
Question 2 of 8What does this page show if
tea-filter.jsnever loads?Read the code, then predict<style> tea-filter:not(:defined) label { display: none; } </style> <tea-filter> <label>Search teas <input type="search"></label> <ul> <li>Green tea</li> <li>Black tea</li> <li>Mint tea</li> <li>Oolong</li> </ul> </tea-filter> <script src="tea-filter.js"></script>Choose an answer to see the explanation.
Question 3 of 8Which part of the tea filter should you hide until
tea-filteris defined?Choose an answer to see the explanation.
Question 4 of 8The tea filter wraps a form with
action="teas"and a box namedq. JavaScript is off. Someone types mint and presses Enter. What happens?Choose an answer to see the explanation.
Question 5 of 8What does
aria-expanded="false"on the More teas button tell a screen reader?Choose an answer to see the explanation.
Question 6 of 8What does the console print when this page runs?
Read the code, then predict<tea-filter> <ul><li>Green tea</li></ul> </tea-filter> <script> class TeaFilter extends HTMLElement { connectedCallback() { this.querySelector("input").addEventListener("input", () => {}); } } customElements.define("tea-filter", TeaFilter); console.log(document.querySelector("tea-filter").matches(":defined")); </script>Choose an answer to see the explanation.
Question 7 of 8Does an HTML web component need shadow DOM?
Choose an answer to see the explanation.
Question 8 of 8Which of these is the poorest fit for an HTML web component?
Choose an answer to see the explanation.
Key takeaways
- An HTML web component wraps HTML that already works, and adds behavior with JavaScript.
- Write the HTML first, wrap it in your tag, then find the parts in
connectedCallback()and add the job. - Build in layers: HTML that works, CSS for both states, and JavaScript on top.
- Hide only the controls that need the script, with
:not(:defined)or ahiddenthe script removes. Never hide the content. - Put searches and actions in real forms and links. Without the script, they still reach the server.
- For a show more button, use a real
<button>witharia-expandedandaria-controls. - No shadow DOM is needed. The page's CSS, scripts, and screen readers all see the real elements.
- Pick a JavaScript web component, or a framework, when there is no HTML to show first.
Remember the one-liner.
Write HTML that works, wrap it in your tag, and let the script add the extra job.
Sources
The facts on this page come from these standards, docs, and posts:
- HTML web components, Jeremy Keith.
- HTML Standard: Upgrading elements after their creation, WHATWG.
- HTML Web Components, Jim Nielsen.
- HTML Web Components: An Example, Jim Nielsen.
- Blinded By the Light DOM, Eric Meyer.
- Disable JavaScript, Chrome for Developers.
- :defined, MDN.
- HTML Web Components, Chris Ferdinandi, Go Make Things.
- Disclosure (Show/Hide) Pattern, W3C ARIA Authoring Practices Guide.
- How to build a show-hide Web Component, Chris Ferdinandi.
- Using custom elements: Implementing a custom element, MDN.
- Shadow DOM: Not by Default, Simon MacDonald, Enhance.
- A year working with HTML Web Components, Hawk Ticehurst.
- An Attempted Taxonomy of Web Components, Zach Leatherman.
- Modern Web Guidance: Web Components orientation, Chrome for Developers.
- Web components with custom elements, Astro Docs.
- How we use Web Components at GitHub, GitHub blog.
Coming next: Customized built-in elements. Extend a real button or input with is="", and learn why Safari refuses it.