Skip to content

Instantly share code, notes, and snippets.

@oscarmarina
Last active August 3, 2020 06:42
Show Gist options
  • Select an option

  • Save oscarmarina/e8982678844c6c35e302a61497b09eea to your computer and use it in GitHub Desktop.

Select an option

Save oscarmarina/e8982678844c6c35e302a61497b09eea to your computer and use it in GitHub Desktop.
/**
* Returns the deepest active element.
*
* @param {HTMLElement} element - The element to search.
* @returns {!HTMLElement} - Active element
*/
export function deepActiveElement(element = document.activeElement) {
let elementActive = element;
// document.activeElement can be null
// https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement
// In IE 11, it can also be an object when operating in iframes.
// In these cases, default it to document.body.
if (!elementActive || elementActive instanceof Element === false) {
elementActive = document.body;
}
if (elementActive.shadowRoot) {
while (elementActive.shadowRoot && elementActive.shadowRoot.activeElement) {
elementActive = elementActive.shadowRoot.activeElement;
}
}
return elementActive;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment