Last active
February 22, 2022 12:33
-
-
Save tadeaspetak/a36f6a4058ba71462f2ecac1ff667fb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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