A custom element can look like a form field without submitting a value or participating in validation. ElementInternals connects the element to browser capabilities that an HTMLElement subclass does not receive automatically: form participation, constraint validation, labels, and default accessibility semantics. Call attachInternals() once in the constructor and retain the returned object. section 9.1
For a form-associated control:
- Declare static formAssociated = true. Give the element a name when using it in a form, then call internals.setFormValue(value) whenever its submitted value changes. The value becomes available through FormData without page-level glue code. section 9.1.1
- Keep attributes, the displayed control, and the submitted value in sync. Use formResetCallback() to restore the initial value and formDisabledCallback(disabled) to update the internal control. section 9.1.1
- Use setValidity(flags, message, anchor) for constraint validation; clear errors with setValidity({}). checkValidity() tests validity and dispatches invalid when appropriate, while reportValidity() also requests browser validation UI when possible. section 9.1.2
Listing 9.1 A form-associated custom element
class FancyInput extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["value", "required", "disabled"];
#value = "";
#input;
constructor() {
super();
this.internals = this.attachInternals();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = template;
this.#input = this.shadowRoot.querySelector("input");
this.#input.addEventListener("input", () => {
this.value = this.#input.value;
});
}
get value() {
return this.#value;
}
set value(v) {
this.#value = String(v ?? "");
this.#input.value = this.#value;
this.internals.setFormValue(this.#value);
this.validate();
}
}
customElements.define("fancy-input", FancyInput);
This form-associated text field attaches internals in its constructor. Its value setter updates the visible input, submitted form value, and validity together; form callbacks complete the reset and disabled behavior. section 9.1.1
ElementInternals also exposes properties such as role, ariaLabel, ariaChecked, and ariaDisabled for defining accessibility defaults on the host. Semantics are not behavior: setting ariaDisabled tells assistive technology about a disabled state, but code must still prevent activation. Prefer a native element when it meets the requirement; a custom widget also needs appropriate focus and keyboard behavior. section 9.3 section 9.3.1
Submitting a form from a shadow-root button
A button inside Shadow DOM does not own the outer form. A form-associated custom element can obtain its owning form from internals.form and have its internal button call requestSubmit(). That runs validation and fires a submit event, preserving the form’s existing submit listener. section 15.6

