Konstantin Solomatov Konstantin Solomatov - 10 months ago 97
Javascript Question

How to check if a dom element is focusable?

Many DOM elements are focusable: divs with tabIndex, input elements, etc. Is there any simple way to check whether an element is focusable than checking a zillion of different cases? Is there a jQuery method for this?

Answer Source

Answer "translated" from here: Which HTML elements can receive focus?

  • <a> or <area> with href
  • Any form elements which aren't disabled
  • iframes
  • Any element with tabindex

Additionaly, I believe that hidden elements can't get focus also.

Assuming that conditions, the following function may help you (assuming it'll always receive an jQuery element):

function canFocus( $el ) {
    if ( $el.is( ":hidden" ) || $el.is( ":disabled" ) ) {
        return false;

    var tabIndex = +$el.attr( "tabindex" );
    tabIndex = isNaN( tabIndex ) ? -1 : tabIndex;
    return $el.is( ":input, a[href], area[href], iframe" ) || tabIndex > -1;