This is a simple way to find all interactive elements in a given context using JavaScript or TypeScript. This can be useful when you need to manage focus within a specific area of your application, such as a modal dialog or a dropdown menu.
export const FOCUSABLE_ELEMENTS = [
'a[href]',
'area[href]',
'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',
'select:not([disabled]):not([aria-hidden])',
'textarea:not([disabled]):not([aria-hidden])',
'button:not([disabled]):not([aria-hidden])',
'iframe',
'object',
'embed',
'[contenteditable]',
'[tabindex]:not([tabindex^="-"])',
]
export const getFocusableNodes = (context: HTMLElement) =>
context.querySelectorAll<HTMLElement>(FOCUSABLE_ELEMENTS.join(','))
export const getOffset = (element: HTMLElement) => {
const rect = element.getBoundingClientRect()
return {
top: rect.top + window.scrollY,
left: rect.left + window.scrollX,
}
}