@@ -29,15 +29,12 @@ const parseLabels = (
2929 return [ ...labels ] . map ( parseToLabel ) . filter ( ( el ) : el is Label => Boolean ( el ) )
3030}
3131
32- const parseToLabel = ( label : HTMLElement ) : Label | undefined => {
33- const textContent = label . textContent
34- ? cleanText ( label . textContent )
35- : undefined
36- if ( ! textContent ) return
32+ const parseToLabel = ( label : HTMLElement ) : Label => {
33+ const textContent = label . textContent ? cleanText ( label . textContent ) : ''
3734 return {
3835 id : label . id ,
3936 attributes : parseNodeMap ( label . attributes ) ,
40- textContent : textContent ,
37+ textContent,
4138 }
4239}
4340
@@ -106,7 +103,10 @@ type AnyParsedElement =
106103 | ParsedMediaElement
107104 | ParsedElementBase
108105
109- const getRelatedElement = (
106+ /**
107+ * Get the element referenced from an attribute
108+ */
109+ const getReferencedElement = (
110110 el : HTMLElement ,
111111 attr : string
112112) : HTMLElement | undefined => {
@@ -115,25 +115,21 @@ const getRelatedElement = (
115115 return document . getElementById ( value ) ?? undefined
116116}
117117
118- const getLabeledBy = ( el : HTMLElement ) : HTMLElement | undefined => {
119- return getRelatedElement ( el , 'aria-labelledby' )
120- }
121-
122- const getDescribedBy = ( el : HTMLElement ) : HTMLElement | undefined => {
123- return getRelatedElement ( el , 'aria-describedby' )
124- }
125-
126118const parseElement = ( el : HTMLElement ) : AnyParsedElement => {
127119 const labels = parseLabels ( ( el as HTMLInputElement ) . labels )
128- const describedBy = getDescribedBy ( el )
129- const labeledBy = getLabeledBy ( el )
120+ const labeledBy = getReferencedElement ( el , 'aria-labelledby' )
121+ const describedBy = getReferencedElement ( el , 'aria-describedby' )
122+ if ( labeledBy ) {
123+ const label = parseToLabel ( labeledBy )
124+ labels . unshift ( label )
125+ }
130126 const base : ParsedElementBase = {
131127 // adding a bunch of fields that are not on _all_ elements, but are on enough that it's useful to have them here.
132128 attributes : parseNodeMap ( el . attributes ) ,
133129 classList : [ ...el . classList ] ,
134130 id : el . id ,
135131 labels,
136- label : labels [ 0 ] ?? ( labeledBy ? parseToLabel ( labeledBy ) : undefined ) ,
132+ label : labels [ 0 ] ,
137133 name : ( el as HTMLInputElement ) . name ,
138134 nodeName : el . nodeName ,
139135 tagName : el . tagName ,
0 commit comments