Skip to content

Commit 78240a2

Browse files
feat: resolve analytics label from associated <label for> element (#228)
1 parent cce49df commit 78240a2

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

src/internal/analytics-metadata/__tests__/labels-utils.test.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,26 @@ describe('getLabelFromElement', () => {
118118
const target2 = container.querySelector('#target2');
119119
expect(getLabelFromElement(target2 as HTMLElement)).toEqual('content');
120120
});
121+
test('returns text of an associated <label for> when the element has no text of its own', () => {
122+
const { container } = render(
123+
<div>
124+
<label htmlFor="target">Column name</label>
125+
<input id="target" type="checkbox" />
126+
</div>
127+
);
128+
const target = container.querySelector('#target');
129+
expect(getLabelFromElement(target as HTMLElement)).toEqual('Column name');
130+
});
131+
test('prefers aria-label over an associated <label for>', () => {
132+
const { container } = render(
133+
<div>
134+
<label htmlFor="target">from label for</label>
135+
<input id="target" type="checkbox" aria-label="from aria-label" />
136+
</div>
137+
);
138+
const target = container.querySelector('#target');
139+
expect(getLabelFromElement(target as HTMLElement)).toEqual('from aria-label');
140+
});
121141
});
122142

123143
describe('processLabel', () => {

src/internal/analytics-metadata/labels-utils.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,5 +160,14 @@ export const getLabelFromElement = (element: HTMLElement | null): string => {
160160
}
161161
}
162162

163+
const id = element.getAttribute('id');
164+
if (id) {
165+
const associatedLabel = element.ownerDocument.querySelector(`label[for="${CSS.escape(id)}"]`);
166+
const associatedText = associatedLabel?.textContent?.trim();
167+
if (associatedText) {
168+
return associatedText;
169+
}
170+
}
171+
163172
return element.textContent ? element.textContent.trim() : '';
164173
};

0 commit comments

Comments
 (0)