Wrap a native input or build your own
Learn when a web component should wrap a native input, slot one from the page, or build the control from scratch, with forms, labels, focus, and events.
- 01Pick a designSay when to slot the page's input, wrap one in a shadow root, or build the control from scratch, and what each one costs.
- 02Make a wrapper act like its inputPass on the value, the attributes,
change, and Enter, delegate focus, and keep one name, on the box. - 03Hide an empty slotShow a hint or a label only when the page gives it words, in every browser.
Should a web component wrap a native input?
It's a quiet morning at Leaf and Kettle. Meena is adding a search to the shop's menu page. She takes Ravi's search box from the kit, puts it in a form, and gives it a name and a label.
Asha tries it. She clicks Find a tea, and nothing happens. She types jasmine in the box and presses Enter. Nothing. She presses Search, and the form sends nothing at all. Should Ravi fix his search box, or build a new one?
Wrap a native input whenever one does the job. The browser then keeps doing the typing, the Enter key, and the autofill, and your class passes on what the page can't reach. Build the control from scratch only when no native element fits, because then the host has to do everything.
Here is Meena's form. Try what Asha tried:
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="find"> <label for="q">Find a tea</label> <tea-search id="q" name="q"></tea-search> <button>Search</button></form><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#find"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>- Line 3 is the label, for the id q. Line 4 is the kit's search box, with that id and the name q.
- Lines 10 to 13 stop the real send, which would load a new page in the Result. They print what the form would send.
Click Find a tea: nothing. Type jasmine in the box, and press Enter: nothing. Press Search: it prints Sent: nothing.
The kit's search box keeps a real <input> in its shadow root. The form can't see it there, as lesson 16.1 showed. There are three ways to put a text box in a component:
- Slot it. The page writes the input inside your tag. Your shadow root only draws around it.
- Wrap it. Your class keeps the input in its shadow root, and the host joins the form for it.
- Build it. There is no input. The host itself takes the typing, the focus, and the value.
Ravi can make a cup of tea two ways. He can put loose leaves in a strainer. The leaves do the brewing, and the strainer only holds them. Or he can sew his own tea bag. Then every seam is his job, and one loose stitch lets the leaves out.
- In real life: The loose leaves
- In JavaScript: A native
<input>, which already takes typing and Enter - In real life: A strainer that holds them
- In JavaScript: A wrapper around that input
- In real life: A tea bag you sew yourself
- In JavaScript: A control built from scratch
- In real life: Every stitch you sew
- In JavaScript: Each thing the host must do itself: focus, keys, value
Keep a real input whenever one does the job, and pass on what the page can't reach. Build from scratch only when nothing native fits.
Why it matters: the choice decides how much code you write. It also decides how much the browser keeps doing for you.
The wrapped and the scratch designs are form-associated custom elements, from lesson 16.1. They work in Chrome 77, Firefox 98, and Safari 16.4 and later, and web-features lists them as Baseline widely available.
How do you wrap a native input in a web component?
A wrapped input can live in two places. It can stay in the page, inside your tag. Or it can live in your shadow root.
Slotting the page's own input
A slot shows the host's children inside its shadow root. The children still belong to the page. So here the page writes the input, and tea-frame only draws a frame and a magnifier around it:
<form id="find"> <label for="q">Find a tea</label> <tea-frame><input id="q" name="q" type="search"></tea-frame> <button>Search</button></form><script src="tea-frame.js"></script><script> const form = document.querySelector("#find"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>class TeaFrame extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `
<style>
:host { display: inline-flex; align-items: center; gap: 6px; padding: 4px 8px; border: 2px solid dimgray; border-radius: 8px; }
::slotted(input) { border: 0; font: inherit; }
</style>
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><circle cx="7" cy="7" r="5" fill="none" stroke="dimgray" stroke-width="2"/><path d="M11 11l4 4" stroke="dimgray" stroke-width="2"/></svg>
<slot></slot>`;
}
}
customElements.define("tea-frame", TeaFrame);- On the page, line 3 is the input, written inside
<tea-frame>. Its id and name are the page's, as on any input. - In the tea-frame.js tab, line 6 draws the frame. Line 7 styles the input with
::slotted(input), which reaches it because it's a child of the host (lesson 11.3). - Line 9 is the magnifier. Line 10 is the slot, where the input shows.
Click Find a tea. The cursor goes into the box. Type jasmine and press Enter: Sent: q=jasmine. Press Search: the same line again. Chrome's tree names the box Find a tea.
Nothing needed passing on. An input's form is the nearest form among its parents, the HTML Standard says. This input's parents are all in the page, so it finds the search form.
Now empty line 6 and run it again. Nobody defines tea-frame, so there's no frame and no magnifier. But the label, Enter, and Search still work. The page works before the script loads, and even if it never does. Mayank calls a shadow root like this one presentational: it only changes the look.
A customer brings a photo of her grandmother's tea garden. Ravi puts it in a frame for the shop wall. The frame is his, but the photo is still hers. If the frame breaks, the photo is still a photo.
- In real life: The frame
- In JavaScript: The shadow root around the slot
- In real life: The customer's photo
- In JavaScript: The page's own
<input> - In real life: It's still her photo
- In JavaScript: Its form, label, and Enter stay the page's
- In real life: A broken frame
- In JavaScript: No script: the input still works
It has a cost. The page has to write the input every time. Your shadow root styles it only through ::slotted(), and the page's own CSS wins over that (lesson 11.3). And the page can change the input in ways your component doesn't expect.
Putting the input in the shadow root
Now the input is the component's own, as in the kit. A control looks for its form only in its own tree, and the shadow root ends that search. So the host has to join the form for it. Try three versions of tea-search.js. Click Find a tea, type jasmine, press Enter, then press Search:
<form id="find"> <label for="q">Find a tea</label> <tea-search id="q" name="q"></tea-search> <button>Search</button></form><script src="tea-search.js"></script><script> const form = document.querySelector("#find"); console.log("Label's control:", form.querySelector("label").control?.localName ?? "none"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>The label has no control, so a click on it does nothing. The box has no form, so Search sends nothing.
class TeaSearch extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true });
this.shadowRoot.innerHTML = `<input id="box" type="search">`;
const box = this.shadowRoot.getElementById("box");
box.addEventListener("input", () => this.#internals.setFormValue(box.value));
}
}
customElements.define("tea-search", TeaSearch);- On the page, line 9 prints the label's control: the element it names, or none.
- In the tab, lines 2 and 3 make the class form-associated and give it its internals, as in lesson 16.1.
- Line 7 attaches the shadow root with
delegatesFocus. Line 8 is the box. - Line 10 hands the form the box's text on every keystroke, with setFormValue().
- An input in a shadow root:
Label's control: none, thenSent: nothing. The label does nothing. - Joined to the form:
Label's control: tea-search, thenSent: q=jasmine. A click on Find a tea puts the cursor in the box. - With Reference Target: the same two lines.
Look closer at the middle choice. A form-associated element can be labelled, so the label points at the host. delegatesFocus sends the click on into the box. But Chrome's tree tells another story:
generic "Find a tea"
searchbox ""The host has the name. The box, which takes focus, has none. That's the trap lesson 13.4 showed. The third choice adds referenceTarget: "box" to line 7. Now a label that points at the host goes on to the box, as in lesson 13.3:
generic ""
searchbox "Find a tea"Two gaps are left. First, Enter: press it in the middle choice, and nothing is sent. The HTML Standard ties Enter to the text box's own form, and this box has none. Second, autofill. Chrome's guide says browsers autofill a native input even in a shadow root, and never a form-associated custom element. So the box can still be autofilled. Pass the page's autocomplete on to it, so the browser knows what to fill. The forwarding section does both.
Why it matters: wrapping keeps the real input's typing and autofill. In return, you pass on what the page can't reach: the value, the label, Enter, and more.
What does a form control built from scratch need?
The third way has no input at all. The host is the control. Here is the same search box, built from scratch:
<form id="find"> <label for="q">Find a tea</label> <tea-textbox id="q" name="q"></tea-textbox> <button>Search</button></form><script src="tea-textbox.js"></script><script> const form = document.querySelector("#find"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script><style>tea-textbox { display: inline-block; min-inline-size: 10em; padding: 4px 8px; border: 2px solid dimgray; }</style>class TeaTextbox extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
connectedCallback() {
this.contentEditable = "plaintext-only";
this.#internals.role = "searchbox";
this.addEventListener("input", () => this.#internals.setFormValue(this.textContent));
}
}
customElements.define("tea-textbox", TeaTextbox);- In the tab, lines 2 and 3 join the form, as before.
- Line 6 makes the host itself editable.
contenteditable="plaintext-only"lets people type plain text into an element, with no bold and no pictures (MDN). - Line 7 gives the host the role searchbox, through its internals, as in lesson 13.2. A screen reader then knows what it is.
- Line 8 hands the form the text on every input event.
- On the page, line 14 draws a border. There's no input to give the box its look.
Click Find a tea. The cursor lands in the box, and Chrome's tree reads searchbox "Find a tea". The label works here, because the host is the control. Safari doesn't use it as the name yet, as lesson 13.4 showed, so give the host a name of its own too. Type jasmine and press Search: Sent: q=jasmine.
Now run it again, and press Enter after jasmine. Nothing is sent, and the box grows a second line. Press Search: Sent: q=jasmine%0A%0A. %0A is a line break, the way a web address writes one. The Enter key went into the text.
Even this box leans on the browser, which does the typing. It still misses what an input gives for free:
- Enter doesn't send the form.
- No
changeevent, ever. - No
placeholder,maxlength, orrequiredfor the browser to read. - No autofill. Chrome's guide says browsers don't autofill form-associated elements or
contenteditable.
It's like baking a loaf of bread for one sandwich. You can do it, but the bakery's bread was right there. Chrome's guide to web components calls rebuilding a native element the most common misuse of custom elements. It says to wrap the real element instead.
So build from scratch only when no native element does the job. A switch or a star rating has no input to wrap. The kit's switch, tea-toggle, is one: its host has the role switch and takes focus itself (lesson 14.1). Then the host carries everything a native input would have given you, starting with its role (MDN):
- a role and its state, through the internals;
- a place in the Tab order, and the keys people expect;
- a value the form sends, and a validity the form checks;
- the four form callbacks from lesson 16.4.
Why it matters: every part a native input does for you, a control from scratch has to do again.
How do you forward events and attributes to an inner input?
A wrapped box is cut off from the page in three ways: its events, its attributes, and its value. The host passes each one on.
Passing events on
Lesson 9.2 sorted the built-in events. The HTML Standard fires input with bubbles and composed set to true. It fires change with bubbles only. So input leaves the shadow root, and change stops there (MDN). Click the box, type tea, press Enter, then press Tab:
<form id="find"> <tea-search name="q"></tea-search> <button>Search</button></form><script src="tea-search.js"></script><script> const form = document.querySelector("#find"); const search = document.querySelector("tea-search"); search.addEventListener("input", (event) => console.log("input from", event.target.localName)); search.addEventListener("change", (event) => console.log("change from", event.target.localName)); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>Each letter prints input from tea-search. Enter and Tab print nothing: the box's change stays in the shadow root.
class TeaSearch extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true });
this.shadowRoot.innerHTML = `<input id="box" type="search">`;
const box = this.shadowRoot.getElementById("box");
box.addEventListener("input", () => this.#internals.setFormValue(box.value));
box.addEventListener("change", () => {
this.dispatchEvent(new Event("change", { bubbles: true }));
});
box.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || event.isComposing) return;
setTimeout(() => {
if (!event.defaultPrevented) this.#internals.form?.requestSubmit();
});
});
}
}
customElements.define("tea-search", TeaSearch);- On the page, lines 9 and 10 listen on the host for input and change, and print each event's target.
- In the tab, lines 11 to 13 hear the box's change and fire a new one from the host.
bubbles: truelets the form hear it too. - Lines 14 to 19 listen for Enter. Line 15 skips other keys. It also skips Enter while
isComposingis true: then an input method, the tool people use to type languages like Chinese or Japanese, is still picking a word. - Line 16 waits one task. Then line 17 asks the form to send itself with
requestSubmit(), unless a listener cancelled the key.
- The value only: three lines of
input from tea-search. Enter and Tab print nothing. - Pass change on: the same, then
change from tea-searchwhen you press Enter. - Pass Enter on too: then
Sent: q=teaas well.
The target is always tea-search, never the input. Events that leave a shadow root are retargeted to the host. Chrome fires the box's change when you press Enter after typing, or when you leave the box with new text. Form events on the JavaScript path compares the two events.
Why does line 16 wait? A real input fires change first, and then sends its form. Waiting a task puts the host's change first too. It also lets a page listener cancel the key in time, as Web Awesome's submitOnEnter() does. And requestSubmit() checks the form first, like a click on its Search button (MDN). Chrome's guide to form-associated elements also asks for the built-in input and change events, not new names.
input is composed, so it crosses the shadow root. Its change isn't, so it stops there. The host fires a change of its own, and that one reaches the page.The kitchen at Leaf and Kettle rings a small bell when an order is ready. Only the cooks hear it. So Ravi, at the counter, listens for the bell and calls out the customer's name. The news is the kitchen's. The voice is his.
- In real life: The kitchen's bell
- In JavaScript: The box's
change, inside the shadow root - In real life: Only the cooks hear it
- In JavaScript:
composedis false - In real life: Ravi calling out the name
- In JavaScript: The host firing its own
change - In real life: The customers hear him
- In JavaScript: Listeners on the page and the form
Web Awesome's input does the same two things. It passes the box's change on from its host, and it sends the form on Enter. Westbrook Johnson explains why built-in events have flags you can't change, while your own events let you choose.
Passing attributes and the value on
The page writes attributes on the host, because that's what it can see. The box inside never sees them. Here the page asks for a placeholder, no autocomplete, and a required field:
<form id="find"> <tea-search name="q" placeholder="Try jasmine" autocomplete="off" required></tea-search> <button>Search</button></form><script src="tea-search.js"></script><script> const form = document.querySelector("#find"); const box = document.querySelector("tea-search").shadowRoot.getElementById("box"); console.log("The box got:", box.placeholder, "|", box.autocomplete, "|", box.required); console.log("Form valid:", form.checkValidity()); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>class TeaSearch extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["placeholder", "autocomplete", "required"];
#internals = this.attachInternals();
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true });
this.shadowRoot.innerHTML = `<input id="box" type="search">`;
this.shadowRoot.getElementById("box").addEventListener("input", () => this.#update());
this.#update();
}
attributeChangedCallback(name, oldValue, newValue) {
const box = this.shadowRoot.getElementById("box");
if (newValue === null) box.removeAttribute(name);
else box.setAttribute(name, newValue);
this.#update();
}
#update() {
const box = this.shadowRoot.getElementById("box");
this.#internals.setFormValue(box.value);
this.#internals.setValidity(box.validity, box.validationMessage, box);
}
get value() {
return this.shadowRoot.getElementById("box").value;
}
set value(text) {
this.shadowRoot.getElementById("box").value = text;
this.#update();
}
}
customElements.define("tea-search", TeaSearch);- On the page, line 2 writes three attributes on the host. Line 9 reads them back from the box. Line 10 asks the form whether it may be sent.
- In the tab, line 3 watches the three attributes. Lines 14 to 19 copy each one onto the box, or remove it, and then update.
- Lines 21 to 25 are
#update(). Line 23 hands the form the box's text. Line 24 copies the box's validity into the host's, with the box as the anchor. So the browser shows its message at the box. - Lines 27 to 34 are the value property. The getter reads the box. The setter writes the box and updates the form.
It prints The box got: Try jasmine | off | true and Form valid: false. Press Search with the box empty. Chrome shows its message, "Please fill out this field.", at the box, and nothing is sent. Type jasmine and press Search: Sent: q=jasmine.
Now delete line 3 of the tab, and run it again. Line 9 prints an empty placeholder, an empty autocomplete, and false. Line 10 prints Form valid: true, and Search sends q= with nothing after it. The attributes sat on the host, and nobody passed them on.
Keep each piece flowing one way. Attributes go from the host to the box. Typing goes from the box to the form value. The value setter writes both. disabled is different: the browser calls formDisabledCallback(). Turn the box off there, and never touch the host's own attribute. Web Awesome's input passes many more attributes on in the same way, like maxlength and inputmode.
Why it matters: every attribute a page might write on an input needs a line in your class. Leave one out, and the page's markup does nothing, with no error.
How does a wrapper handle focus and its name?
Focus is the easy part. Lesson 14.1 showed that delegatesFocus does most of it. A click on the host, a focus() call, or Tab puts focus in the box, and the host matches :focus. With a form-associated host, a click on its label does the same. You saw that in the wrapper playground. MDN describes the option.
The name is harder. A screen reader reads the name of the element that has focus. That's the box. But the page can only reach the host. Here is a common try: the page writes aria-label on the host, and the class copies it onto the box:
<tea-search aria-label="Find a tea"></tea-search><script src="tea-search.js"></script><script> const search = document.querySelector("tea-search"); const box = search.shadowRoot.getElementById("box"); console.log("Host:", search.ariaLabel, "| Box:", box.ariaLabel);</script>class TeaSearch extends HTMLElement {
static observedAttributes = ["aria-label"];
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true });
this.shadowRoot.innerHTML = `<input id="box" type="search">`;
}
attributeChangedCallback(name, oldValue, newValue) {
this.shadowRoot.getElementById("box").setAttribute("aria-label", newValue);
}
}
customElements.define("tea-search", TeaSearch);- In the tab, line 2 watches aria-label. Line 11 copies it onto the box.
- On the page, line 6 prints the aria-label of both.
It prints Host: Find a tea | Box: Find a tea. Here is Chrome's tree:
generic "Find a tea"
searchbox "Find a tea"Two nodes now carry the same name. The box needs it, because it takes focus. The host shouldn't have it. It has no role, and WAI-ARIA forbids naming the generic role. Chrome names it anyway. And the class shouldn't take the attribute off the host: it's the page's.
aria-label to the box puts the name on two nodes.Asha books a table for one. The waiter puts a name card on the table, and another on her chair. Then a new waiter reads the table out loud: Asha, Asha. One card is enough, on the chair where she sits.
- In real life: The card on the table
- In JavaScript: A name on the host
- In real life: The card on her chair
- In JavaScript: A name on the box that takes focus
- In real life: Reading the table out: Asha, Asha
- In JavaScript: Two nodes with the same name
- In real life: One card, on her chair
- In JavaScript: One name, on the box
So give the box one name, from one place. Don't name the host through its internals either: Chrome's guide warns that it would override the page's label. Three ways work:
- Pass a plain attribute on, but not
aria-label. The kit's search box reads alabelattribute and puts it on the box. The host never gets a name. - Keep a label inside the shadow root, and take its words from a slot. The next section does this.
- Let a page
<label for>reach the box with Reference Target. Where that's missing, point the box at the label with ariaLabelledByElements, as the kit's quantity does. The label still names the host there too, so the name sits on two nodes.
Reference Target is on by default only in Chrome 152 and later (Chrome's release notes). Firefox 144 and Safari 26 have it only behind a setting, and the standard is still an open pull request. Nolan Lawson explains why names across shadow roots are so hard.
One more rule, from lesson 14.1. A host built from scratch has its own role and state, so it takes focus itself, with a tabindex. Never delegate its focus: a screen reader would land inside, and miss the host's state.
Why it matters: focus is easy to pass on. A name has to sit once, on the element that has focus.
How do you hide an empty hint or label slot?
A wrapper often draws more than the box: a label above it, and a hint under it. Web Awesome's input has a slot for each, and the page puts its own words in. Each slot can hold fallback content: the words between <slot> and </slot>, which show when nothing is assigned (MDN). That covers the label. A hint has no sensible fallback. An empty hint box should simply go away.
Here is tea-search with both slots. Try four pages:
<form id="find"> <tea-search name="q"></tea-search></form><script src="tea-search.js"></script><script> setTimeout(() => { const search = document.querySelector("tea-search"); const hint = search.shadowRoot.getElementById("hint"); console.log("has-hint:", search.matches(":state(has-hint)"), "| hint box:", getComputedStyle(hint).display); });</script>No slotchange fires, so the state never comes, and the hint box stays hidden. The label shows its fallback, Search teas.
class TeaSearch extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true });
this.shadowRoot.innerHTML = `
<style>
#hint { margin: 4px 0 0; padding-inline-start: 8px; border-inline-start: 3px solid seagreen; }
:host(:not(:state(has-hint))) #hint { display: none; }
</style>
<label for="box"><slot name="label">Search teas</slot></label>
<input id="box" type="search" aria-describedby="hint">
<p id="hint"><slot name="hint"></slot></p>`;
const box = this.shadowRoot.getElementById("box");
box.addEventListener("input", () => this.#internals.setFormValue(box.value));
const hint = this.shadowRoot.querySelector('slot[name="hint"]');
hint.addEventListener("slotchange", () => {
const words = hint.assignedNodes().some((node) => node.textContent.trim());
if (words) this.#internals.states.add("has-hint");
else this.#internals.states.delete("has-hint");
});
}
}
customElements.define("tea-search", TeaSearch);- Line 13 is a label inside the shadow root, for the box. Its words come from the label slot. Search teas is the fallback.
- Line 14 is the box.
aria-describedby="hint"points at the hint's paragraph. Both sit in the same shadow root, so the reference works, as Westbrook Johnson shows. - Line 15 is the hint's paragraph, around the hint slot.
- Line 11 hides the paragraph unless the host has the has-hint state, a custom state.
- Lines 18 to 23 set that state on each slotchange. Line 20 asks whether any assigned node has words.
trim()drops spaces, so a node of only spaces doesn't count, as in lesson 8.4. - On the page, line 6 waits a moment, so slotchange has run. Line 9 prints the state and the hint box's display.
- No hint:
has-hint: false | hint box: none. - A hint:
has-hint: true | hint box: block. - Only a space:
has-hint: false | hint box: none. - A label and a hint:
has-hint: true | hint box: block, and the label reads Find a tea.
Here is Chrome's tree for the box, with no hint and then with the last choice:
searchbox "Search teas"
searchbox "Find a tea", description: "Try a name, like jasmine"The label inside names the box, with the page's words. That's the cleanest fix for the last section's problem: one label and one name, with no Reference Target needed. The hint becomes the box's description, because the reference stays in one tree.
slotchange check looks for words. With words, the host gets the has-hint state, and the hint box shows. With none, the box stays hidden, so no empty line sits under the text box.Leaf and Kettle has a small board by the till: Today's special. Some days there is no special. Then Meena takes the board down. An empty board only makes people ask.
- In real life: The board by the till
- In JavaScript: The hint box around the slot
- In real life: The day's special
- In JavaScript: Words the page puts in the slot
- In real life: Taking the board down
- In JavaScript:
display: nonewhile there's nohas-hintstate - In real life: Meena checking the menu each morning
- In JavaScript: The
slotchangecheck
What about :has-slotted?
:has-slotted matches a slot with something assigned (MDN). With it, CSS alone could hide the box. Lessons 8.4 and 11.3 showed two catches:
- Only Firefox 136 and later ship it. Chrome has it behind a flag (Chrome Platform Status), and Safari has none.
- A single space counts as content.
So keep the slotchange check and the state. If you add a :has-slotted rule as an extra, point it the safe way, as lesson 11.3 explained: hide only when the browser can tell the slot is empty.
Why it matters: an empty hint box leaves a gap and a stray line under the field. A check in the class hides it everywhere.
When should you wrap, slot, or build a form control?
Time to put them side by side, on one search form. The page is the same each time. Click Find a tea, type jasmine, press Enter, then press Search:
<form id="find"> <label for="q">Find a tea</label> <tea-frame><input id="q" name="q" type="search"></tea-frame> <button>Search</button></form><script src="tea.js"></script><script> const form = document.querySelector("#find"); form.addEventListener("change", () => console.log("change")); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>Enter prints change and sends the form. Search sends it again. The input is the page's, so nothing needs passing on.
- Slot the page's input:
change,Sent: q=jasmine, andSent: q=jasmineagain. - Wrap it, value only: only
Sent: q=jasmine, from Search. - Wrap it, and pass things on: the same three lines as the slotted input.
- Build it from scratch: Enter adds a line, and Search prints
Sent: q=jasmine%0A%0A. No change.
Read the table across, one question per row:
| Question | Slot the page's input | Wrap an input in the shadow root | Build it from scratch |
|---|---|---|---|
| Who writes the input? | The page writes it, inside your tag. | Your class writes it, in its shadow root. | Nobody. The host is the control. |
| Is it sent with the form? | Yes, as it is. | Only when the host joins the form and calls setFormValue(). | Only when the host joins the form and calls setFormValue(). |
Does a page <label for> name it? | Yes. | It names the host. Reference Target sends it on to the box, in Chrome 152 and later. | Yes in Chrome and Firefox. Safari doesn't use the label as its name yet. |
| Does Enter send the form? | Yes. | Only if the host passes Enter on. | Only if you write it. |
Does the page hear change? | Yes. | Only if the host fires its own. | Only if you fire one. |
| Can the browser autofill it? | Yes. | Yes. Pass autocomplete on to the box. | No. Browsers don't autofill form-associated custom elements. |
| Does it work before the script loads? | Yes. The input is in the page. | No. | No. |
| Can your CSS style every part? | Only the input itself, through ::slotted(). | Yes. | Yes. |
| When is it the right choice? | When the page must work without JavaScript, or owns the field. | When a native input does the job: text, numbers, dates. | When no native element does the job, like a switch or a star rating. |
In short: slot when the page owns the field, or must work without JavaScript. Wrap when a native input does the job, which is most of the time. Build only when nothing native fits.
Making the kit's search box a form control
Back to Meena's search form. The kit's new version, kitAfter165, makes tea-search a wrapper that passes everything on. Here is her form with it:
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="find"> <label for="q">Find a tea</label> <tea-search id="q" name="q" placeholder="Try jasmine" required></tea-search> <button>Search</button> <button type="reset">Clear</button></form><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#find"); form.addEventListener("change", () => console.log("change:", form.elements.q.value)); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>- Line 3 is the label. Line 4 is the search box, with an id, a name, a placeholder, and required.
- Line 6 is a Clear button, which resets the form.
- Line 11 prints each change the form hears, with the search box's value.
form.elements.qfinds the host by its name, as in lesson 16.1.
- Press Search with the box empty. Chrome shows "Please fill out this field." at the box, and moves focus there. Nothing prints.
- Type jasmine, and press Enter. It prints
change: jasmine, thenSent: q=jasmine. - Press Clear. The box is empty again.
Chrome's tree names the box, and only the box:
generic ""
searchbox "Find a tea"Here is the start of the new class, from tea-kit/tea-search.js:
export class TeaSearch extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["label", "placeholder", "autocomplete", "required"];
#internals = attachInternals(this);
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true });
this.shadowRoot.adoptedStyleSheets = [base, sheet];
this.shadowRoot.append(template.content.cloneNode(true));
if (hasReferenceTarget) this.shadowRoot.referenceTarget = "box";
const box = this.shadowRoot.getElementById("box");
box.addEventListener("input", () => this.#update());
box.addEventListener("change", () => this.dispatchEvent(new Event("change", { bubbles: true })));
box.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || event.isComposing) return;
setTimeout(() => {
if (!event.defaultPrevented) this.#internals.form?.requestSubmit();
});
});
this.#update();
}
connectedCallback() {
if (!this.id || this.hasAttribute("label")) return;
const label = this.getRootNode().querySelector(`label[for="${CSS.escape(this.id)}"]`);
if (!label) return;
const box = this.shadowRoot.getElementById("box");
box.removeAttribute("aria-label");
if (!hasReferenceTarget) box.ariaLabelledByElements = [label];
}
attributeChangedCallback(name, oldValue, newValue) {
const box = this.shadowRoot.getElementById("box");
if (name === "label") {
box.setAttribute("aria-label", newValue ?? "Search teas");
return;
}
if (newValue === null) box.removeAttribute(name);
else box.setAttribute(name, newValue);
this.#update();
}- Lines 2 and 4 make it form-associated. Its internals are listed for checkers like axe, as in lesson 15.3.
- Line 3 watches four attributes. Lines 39 and 40 pass the last three on to the box.
- Line 11 sets Reference Target, where the browser has it.
- Line 13 updates the form value on every keystroke. Line 14 passes change on.
- Lines 15 to 20 pass Enter on, as in the events playground.
- Lines 24 to 31 run when it joins the page. With an id and a page label, line 29 drops the default name, Search teas. Without Reference Target, line 30 points the box at the label.
Further down, the class adds three form callbacks from lesson 16.4. A reset empties the box. A disabled state turns the box off. The Back button's restore sets the value. It also gets the same members as the quantity: form, name, a value you can set, validity, and the two checks.
The course's test runs pages from earlier lessons with kitAfter164 and kitAfter165. Every printed line, box, focus, and tree stays the same. The JSDoc and custom-elements.json document the new attributes, members, and the change event.
Why it matters: the kit's search box now works in a form the way an input does, from plain HTML.
Common mix-ups
- "An input in my shadow root is sent with the form." No. Its search for a form stops at the shadow root. The host has to join the form and hand over the value.
- "A slotted input is hidden from the form." No. It's still the page's child, so it finds its form, and it works even before your script runs.
- "The page hears every event from my inner input." No.
inputgets out, butchangeisn't composed. Fire your own from the host. - "Enter in my wrapper sends the form." No. The box has no form of its own. Pass Enter on with
requestSubmit(). - "Attributes on the host reach the input." No. Watch each one and copy it onto the box.
- "delegatesFocus passes the label's name on too." No. It moves focus only. The name stays on the host.
- "Copying aria-label to the box moves the name." No. The host keeps its own, so the name shows twice.
- "Reference Target works in every browser." No. It's on by default only in Chrome 152 and later.
- "A control from scratch gets autofill like an input." No. Browsers don't autofill form-associated custom elements.
- ":has-slotted hides empty slots everywhere." No. Only Firefox ships it, and it counts a single space as content.
Practice exercises
No script defines tea-frame. Line 6 prints tea-frame defined: false. Predict what line 7 prints, then run it.
<form id="find"> <tea-frame><input name="q" value="sencha"></tea-frame></form><script> const form = document.querySelector("#find"); console.log("tea-frame defined:", customElements.get("tea-frame") !== undefined); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing");</script><form id="find"> <tea-frame><input name="q" value="sencha"></tea-frame></form><script> const form = document.querySelector("#find"); console.log("tea-frame defined:", customElements.get("tea-frame") !== undefined); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing");</script>It prints Sent: q=sencha. The input is the page's own, inside the tag, so it finds the form like any input. The tag doesn't need to be defined.
The tea-search.js tab is the first wrapper of the playground. Line 7 fires a change at the box, inside the shadow root. Predict what the page prints, then run it.
<tea-search></tea-search><script src="tea-search.js"></script><script> const search = document.querySelector("tea-search"); search.addEventListener("change", () => console.log("The page heard change")); const box = search.shadowRoot.getElementById("box"); box.dispatchEvent(new Event("change", { bubbles: true })); console.log("Done");</script><tea-search></tea-search><script src="tea-search.js"></script><script> const search = document.querySelector("tea-search"); search.addEventListener("change", () => console.log("The page heard change")); const box = search.shadowRoot.getElementById("box"); box.dispatchEvent(new Event("change", { bubbles: true })); console.log("Done");</script>It prints only Done. Line 7 fires change at the box with the same flags as the box's own change: it bubbles, but isn't composed. So it stops at the shadow root, and the page's listener on line 5 never hears it.
Type tea in the box and press Tab. The page prints nothing: the form never hears the change. Fix the tea-search.js tab. What does the page print then?
<form id="find"> <tea-search name="q"></tea-search></form><script src="tea-search.js"></script><script> const form = document.querySelector("#find"); form.addEventListener("change", () => console.log("change:", new FormData(form).get("q")));</script><form id="find"> <tea-search name="q"></tea-search></form><script src="tea-search.js"></script><script> const form = document.querySelector("#find"); form.addEventListener("change", () => console.log("change:", new FormData(form).get("q")));</script>The tea-search.js tab now hears the box's change and fires a new one from the host, with bubbles set. The host is in the page, so the form hears it and prints change: tea.
The page writes a placeholder on the host, but it prints Placeholder: none. Fix the tea-search.js tab so the box gets it. What does the page print then?
<tea-search name="q" placeholder="Try jasmine" required></tea-search><script src="tea-search.js"></script><script> const box = document.querySelector("tea-search").shadowRoot.getElementById("box"); console.log("Placeholder:", box.placeholder || "none");</script><tea-search name="q" placeholder="Try jasmine" required></tea-search><script src="tea-search.js"></script><script> const box = document.querySelector("tea-search").shadowRoot.getElementById("box"); console.log("Placeholder:", box.placeholder || "none");</script>Line 3 of the tea-search.js tab now watches placeholder too, so attributeChangedCallback() copies it onto the box. The page prints Placeholder: Try jasmine.
Type chai and press Enter. Nothing prints. Make Enter send the form, the way it does from a plain input. What does Enter print then?
<form id="find"> <tea-search name="q"></tea-search> <button>Search</button></form><script src="tea-search.js"></script><script> const form = document.querySelector("#find"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script><form id="find"> <tea-search name="q"></tea-search> <button>Search</button></form><script src="tea-search.js"></script><script> const form = document.querySelector("#find"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>The tea-search.js tab now listens for keydown. On Enter, it waits a task and calls requestSubmit() on the host's form, so the submit listener prints Sent: q=chai.
Two search boxes: the first has a hint, the second has none. Both hint boxes stay hidden, and it prints Hint box: none twice. Fix the tea-search.js tab. What do the two lines print then?
<tea-search name="q"><span slot="hint">Try a name, like jasmine</span></tea-search><tea-search name="q2"></tea-search><script src="tea-search.js"></script><script> setTimeout(() => { for (const search of document.querySelectorAll("tea-search")) { console.log("Hint box:", getComputedStyle(search.shadowRoot.getElementById("hint")).display); } });</script><tea-search name="q"><span slot="hint">Try a name, like jasmine</span></tea-search><tea-search name="q2"></tea-search><script src="tea-search.js"></script><script> setTimeout(() => { for (const search of document.querySelectorAll("tea-search")) { console.log("Hint box:", getComputedStyle(search.shadowRoot.getElementById("hint")).display); } });</script>The tea-search.js tab now listens for slotchange on the hint slot and sets the has-hint state when it finds words. The first search box shows its hint, and the second hides its empty box: Hint box: block, then Hint box: none.
Check your understanding
Question 1 of 8This page's tea-search.js is the first wrapper of the playground: a text box in a shadow root, and nothing else. What does it print?
Read the code, then predict<form id="find"> <tea-search name="q"></tea-search> </form> <script src="tea-search.js"></script> <script> const form = document.querySelector("#find"); document.querySelector("tea-search").shadowRoot.getElementById("box").value = "sencha"; console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); </script>Choose an answer to see the explanation.
Question 2 of 8A text box sits in a shadow root. Which of its events does a listener on the page hear?
Choose an answer to see the explanation.
Question 3 of 8A form-associated wrapper delegates focus, and a page label points at the host's id. In Chrome, with no Reference Target, what does the label name?
Choose an answer to see the explanation.
Question 4 of 8Why doesn't Enter in a wrapped text box send the page's form?
Choose an answer to see the explanation.
Question 5 of 8Which design keeps the browser's autofill working?
Choose an answer to see the explanation.
Question 6 of 8The page writes aria-label on the host, and the class copies it onto the box. What does Chrome's tree show?
Choose an answer to see the explanation.
Question 7 of 8Which browsers support :has-slotted without a setting?
Choose an answer to see the explanation.
Question 8 of 8When is building a form control from scratch the right choice?
Choose an answer to see the explanation.
Key takeaways
- There are three ways: slot the page's input, wrap one in your shadow root, or build the control from scratch.
- A slotted input is the page's own. Its form, label, Enter, and autofill all just work, even with no script.
- A wrapped input can't reach the page's form. The host joins with
formAssociatedandsetFormValue(). - Pass on what the box can't do from inside:
change, Enter, attributes likeplaceholder,autocomplete, andrequired, the validity, and the value. delegatesFocusmoves focus, never a name. Put one name on the box: a label inside, a plain attribute, or Reference Target.- Hide an empty hint with a slotchange check and a custom state. :has-slotted ships only in Firefox.
- Build from scratch only when no native element fits. Then the host carries the role, focus, keys, value, and validity, and gets no autofill.
Remember the one-liner.
Wrap a real input whenever one does the job, and pass on what the page can't reach. Build from scratch only when nothing native fits.
Sources
The facts on this page come from these standards, docs, source files, and posts:
- Web Components orientation: decide whether you even need a custom element, Chrome for Developers, Modern Web Guidance.
- Reset the form owner, HTML Standard.
- Presentational shadow DOM, Mayank.
- Implicit submission, HTML Standard.
- Customize the styling of autofilled form fields, Chrome for Developers, Modern Web Guidance.
- Element: attachShadow(), Parameters, MDN.
- Chrome 152 release notes: Reference Target for cross-root ARIA, Chrome for Developers.
- Add reference target, whatwg/html pull request 10995, WHATWG.
- contenteditable, the plaintext-only value, MDN.
- ElementInternals: role property, MDN.
- Form-associated custom elements, Chrome for Developers, Modern Web Guidance.
- Event: composed property, MDN.
- Common input element events, HTML Standard.
- composed: true considered harmful?, Westbrook Johnson, DEV.
- HTMLFormElement: requestSubmit() method, MDN.
- input.ts at v3.15.0: handleChange() and handleKeyDown(), Web Awesome.
- submit-on-enter.ts at v3.15.0: submitOnEnter(), Web Awesome.
- Shadow DOM and accessibility: the trouble with ARIA, Nolan Lawson.
- WAI-ARIA 1.2: the generic role, W3C.
- Element: ariaLabelledByElements property, MDN.
- <slot>: the HTML Web Component Slot element, MDN.
- HTMLSlotElement: assignedNodes() method, MDN.
- HTMLSlotElement: slotchange event, MDN.
- Who doesn't love some <slot />s?, Westbrook Johnson, DEV.
- input.ts at v3.15.0: the label and hint slots, Web Awesome.
- slot.ts at v3.15.0: HasSlotController, Web Awesome.
- :has-slotted, MDN.
- :has-slotted pseudo selector, Chrome Platform Status.
- Form-associated custom elements, web-features, on Web Platform Status.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Build a switch. It builds a control from scratch, end to end: a switch that submits, resets, checks itself, and works with a keyboard and a screen reader.