Load all focusable elements with JavaScript

Categories

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
JavaScript
/**
 * 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)'
  );
};

Hello, I’m Andy and I’ll help you build fast & visually stunning websites.

I am currently setting up a new creative agency called Set Creative Studio and we are taking on projects for 2022, so if you have a project in mind, get in touch.