We have some custom components which can be used for user input (CustomSelect, SegmentedControl, CustomCheckbox, etc).
In some cases, these internally use the semantic html tag like radiogroup or select, but in some cases, the markup is completely written using div and span elements and accessibility is provided using aria attributes. For such implementations, is there a way to associate a label element to them, to make them behave like native form inputs wrt label behaviour, or better, is there a way to get them treated like native form inputs?
Things that come to mind:
Are there any existing patterns for this?
You need to do three things:
aria-labelledby.Note that you can use a real <label> element but it would mainly be for more readable code, so it's easy to spot the label associated with the element. You most likely (*) cannot use the for attribute of the <label> element because the ID specified must be of a "labelable element", which is defined as:
(*) You can use the for attribute if you have a custom element with a form-associated attribute of true. A <label> can be used on a "form-associated custom element"
See https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-face-example.
I have not created a custom form element before but the doc sounds like a real <label for="ID"> can be used with it, in which case you don't need aria-labelledby or javascript.