Load all focusable elements with JavaScript

A handy helper function that will load all user-focusable elements inside a parent element for you.


It’s handy to know what elements are focusable when you are building accessible, interactive user interface elements. This is especially the case if you are planning to trap focus, or toggle your interactive element’s state when user focus escapes it.

This little helper function will find all focusable child elements—specifically, user-focusable elements—of a passed parent element:

Code language
js
/**
 * Returns back a NodeList of focusable elements
 * that exist within the passed parent HTMLElement, or
 * an empty array if no parent passed.
 *
 * @param {HTMLElement} parent HTML element
 * @returns {(NodeList|Array)} The focusable elements that we can find
 */
const getAllFocusableElements = parent => {
  if (!parent) {
    console.warn('You need to pass a parent HTMLElement');
    return []; // Return array so length queries will work
  }

  return parent.querySelectorAll(
    'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled]), details:not([disabled]), summary:not(:disabled)'
  );
};