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

Hello, I’m Andy and I’ll help you to level up your front-end development skills.

I'm a designer and front-end developer who has worked in the design and web industries for over 15 years, and in that time, I have worked with some of the largest organisations in the world, like Google, Harley-Davidson, BSkyB, Unilever, The Natural History Museum, Oracle, Capita, Vice Media and the NHS.

On Piccalilli, I share my knowledge and experience to make you a better front-end developer.

I'm the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. Check out what we're all about.