Skip to content

Instantly share code, notes, and snippets.

@tadeaspetak
Last active February 22, 2022 12:33
Show Gist options
  • Save tadeaspetak/a36f6a4058ba71462f2ecac1ff667fb8 to your computer and use it in GitHub Desktop.
Save tadeaspetak/a36f6a4058ba71462f2ecac1ff667fb8 to your computer and use it in GitHub Desktop.
export const getFocusableElements = (parent?: HTMLElement | null): HTMLElement[] => {
if (!parent) return [];
return Array.from(parent.querySelectorAll("a[href], button, input, textarea, select, details,[tabindex]"))
.filter(
(el) => el.getAttribute("tabindex") !== "-1" && !el.hasAttribute("disabled") && !el.getAttribute("aria-hidden")
)
// sort tabindexes as follows: 1, 2, 3, 4, ..., 0, 0, 0
.sort((a, b) => {
const aIndex = Number(a.getAttribute("tabindex")) ?? 0; // no `tabindex` means `tabindex=0` on a focusable element
const bIndex = Number(b.getAttribute("tabindex")) ?? 0;
if (aIndex === bIndex) return 0;
if (aIndex === 0) return 1;
if (bIndex === 0) return -1;
return aIndex < bIndex ? -1 : 1;
}) as HTMLElement[];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment