Skip to content

Vanilla :tabbable Selector #5

@bpceee

Description

@bpceee

You might not need jQuery is a good place to find Vanilla JS equivalents of jQuery methods.
However, some jQuery unique selector couldn't be found there. Like :tabbable Selector.

Elements of the following type are tabbable if they do not have a negative tab index and are not disabled: input, select, textarea, button, and object. Anchors are focusable if they have an href or positive tabindex attribute. area elements are focusable if they are inside a named map, have an href attribute, and there is a visible image using the map. All other elements are tabbable based solely on their tabindex attribute and visibility.

Based the quoted document above, we can write an implementation like this:

Array.from(
  document.querySelectorAll(`
    input:not([tabindex^="-"]):not([disabled]),
    select:not([tabindex^="-"]):not([disabled]),
    textarea:not([tabindex^="-"]):not([disabled]),
    button:not([tabindex^="-"]):not([disabled]),
    a[href]:not([tabindex^="-"]):not([disabled]),
    [tabindex]:not([tabindex^="-"]):not([disabled])
  `)
).filter(ele => ele.offsetParent !== null)

The filter here is to make sure the selected elements are visible(in the layout). According to https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent, offsetParent returns null when the element has style.display set to none. (including children elements)

Well, this doesn't handle object and map element. The rules for these two element are a little bit tricky, and they are rarely used anyway...
Also, I find that contrary to the jQuery's doc, a disabled object element is focusable in Chrome.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions