dom_get-focusable.js

import convertElements from './convert-elements';
import visible from './visible';

/**
 * @module getFocusable
 * @description Get focusable elements inside a passed container and return as an array.
 *
 * @since 1.0.0
 *
 * @requires convertElements
 * @requires visible
 *
 * @param {Document|HTMLElement} container The parent to search for focusable elements inside.
 *
 * @return {Array} An array of focusable elements.
 *
 * @example
 * import { getFocusable } from  "@gravityforms/utils";
 *
 * function Example() {
 *  const focusable = getFocusable( container );
 * 	// store first and last visible item
 * 	const firstFocusableEl = focusable[ 0 ];
 * 	const lastFocusableEl = focusable[ focusable.length - 1 ];
 * }
 *
 */
export default function getFocusable( container = document ) {
	const focusable = convertElements(
		container.querySelectorAll(
			'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
		)
	);
	return focusable.filter( ( item ) => visible( item ) );
}