Skip to content

Instantly share code, notes, and snippets.

@gokhantaskan
Last active February 11, 2023 09:50
Show Gist options
  • Save gokhantaskan/31f145ac0b64a44678b5b4c8759e4d70 to your computer and use it in GitHub Desktop.
Save gokhantaskan/31f145ac0b64a44678b5b4c8759e4d70 to your computer and use it in GitHub Desktop.
Find the first focusable element inside a DOM element
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