Skip to content

Commit

Permalink
fix: Self-referring aria-labelledby (#91)
Browse files Browse the repository at this point in the history
Co-authored-by: Francesco Longo <[email protected]>
  • Loading branch information
fralongo and Francesco Longo authored Aug 26, 2024
1 parent acc9a5f commit dc6d8c1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ describe('getLabelFromElement', () => {
const target = container.querySelector('#target');
expect(getLabelFromElement(target as HTMLElement)).toEqual('second content');
});
test('returns text content aria-labelledby refers to the element itself', () => {
const { container } = render(
<div id="target" aria-labelledby="target">
content
</div>
);
const target = container.querySelector('#target');
expect(getLabelFromElement(target as HTMLElement)).toEqual('content');
});
test('returns empty string if aria-labelledby element does not exist', () => {
const { container } = render(
<div>
Expand Down
4 changes: 3 additions & 1 deletion src/internal/analytics-metadata/labels-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ export const getLabelFromElement = (element: HTMLElement | null): string => {
const ariaLabelledBy = element.getAttribute('aria-labelledby');
if (ariaLabelledBy) {
const elementWithLabel = document.querySelector(`[id="${ariaLabelledBy.split(' ')[0]}"]`);
return getLabelFromElement(elementWithLabel as HTMLElement);
if (elementWithLabel !== element) {
return getLabelFromElement(elementWithLabel as HTMLElement);
}
}

return element.textContent ? element.textContent.trim() : '';
Expand Down

0 comments on commit dc6d8c1

Please sign in to comment.