Skip to main content Accessibility Feedback

How to get the first and last focusable elements in the DOM

Heydon shared a neat JavaScript trick on Twitter the other week for getting all focusable elements in the DOM, and narrowing it down to the first or last element.

We can get all focusable elements using querySelectorAll() and a comma-separated list of elements to target. We want to look for buttons, links, form eleements, and anything with a tabindex that’s not -1.

var focusable = document.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"]');

This returns a node list from which we can grab the first or last element as needed.

var focusable = document.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not(tabindex="-1"]');
var firstFocusable = focusable[0];
var lastFocusable = focusable[focusable.length - 1];

Thanks Heydon!


🚀 I just relaunched my Vanilla JS Pocket Guides with new code examples and real projects to help tie everything you’ll learn together. Check it out.

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips