Last active
February 11, 2023 09:50
-
-
Save gokhantaskan/31f145ac0b64a44678b5b4c8759e4d70 to your computer and use it in GitHub Desktop.
Find the first focusable element inside a DOM element
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 function findFirstFocusableElement( | |
element: HTMLElement | null, | |
tags: string = "", | |
{ withDefaults } = { withDefaults: false } | |
) { | |
if (!element) return; | |
const defaults = | |
"a[href], button, input, textarea, select, details, [tabindex]:not([tabindex='-1'])"; | |
const focusableElements = element.querySelectorAll( | |
withDefaults | |
? tags.length | |
? `${defaults}, `.concat(tags) | |
: defaults | |
: tags | |
); | |
if (focusableElements.length > 0) { | |
return focusableElements[0] as HTMLElementTagNameMap[keyof HTMLElementTagNameMap]; | |
} | |
} | |
const firstInvalidInput = findFirstFocusableElement( | |
document.querySelector("form"), | |
".is-invalid textarea, .is-invalid input", | |
{ withDefaults: false } | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment