get focus element javascript code example

Example 1: set focus javascript

document.getElementById("ThingToSetFocusOn").focus();

Example 2: Javascript find element with focus

var currentElementWithFocus=document.activeElement;

Example 3: javascript get focusable elements

/**
 * Gets keyboard-focusable elements within a specified element
 * @param {HTMLElement} [element=document] element
 * @returns {Array}
 */
function getKeyboardFocusableElements (element = document) {
  return [...element.querySelectorAll(
    'a, button, input, textarea, select, details,[tabindex]:not([tabindex="-1"])'
  )]
    .filter(el => !el.hasAttribute('disabled'))
}

Tags:

Html Example