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
 * 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)'


If you liked this post, you might like these ones, too

  1. Picture element as a progressive enhancement

    🔥 A handy quick tip.

  2. Squishy button active state

    🔥 A handy quick tip.

  3. How to use the lesson project files to rescue your project

    Sometimes you get a bit stuck in a course, so this quick tip teaches you how to get back on track


Become a supporter by joining the Piccalilli Membership

For as little a $5 per month, you can get access to a private, friendly community, get a weekly newsletter and help to make as much content free as possible around here. If you join the $10 per month supporters club, you get access to premium tutorials and free access to mini courses!

Become a member

Sign up for updates

Stay up to date with updates from Piccalilli. You’ll get alerted as soon as any new content gets published. You’ll also get updates on upcoming courses and membership features! You can unsubscribe at any time, too.