Added method to retrieve element or throw

This commit is contained in:
squidfunk
2020-02-14 09:52:22 +01:00
parent 718b51bac9
commit 8c92565b7b
6 changed files with 50 additions and 29 deletions

View File

@@ -32,7 +32,7 @@
* @param selector - Query selector
* @param node - Node of reference
*
* @return Element
* @return Element or nothing
*/
export function getElement<T extends HTMLElement>(
selector: string, node: ParentNode = document
@@ -40,6 +40,38 @@ export function getElement<T extends HTMLElement>(
return node.querySelector<T>(selector) || undefined
}
/**
* Retrieve an element matching a query selector or throw a reference error
*
* @template T - Element type
*
* @param selector - Query selector
* @param node - Node of reference
*
* @return Element
*/
export function getElementOrThrow<T extends HTMLElement>(
selector: string, node: ParentNode = document
): T {
const el = getElement<T>(selector, node)
if (typeof el === "undefined")
throw new ReferenceError(
`Missing element: expected "${selector}" to match an element`
)
return el
}
/**
* Retrieve the currently active element
*
* @return Element
*/
export function getActiveElement(): HTMLElement | undefined {
return document.activeElement instanceof HTMLElement
? document.activeElement
: undefined
}
/**
* Retrieve all elements matching the query selector
*
@@ -55,16 +87,3 @@ export function getElements<T extends HTMLElement>(
): T[] {
return Array.from(node.querySelectorAll<T>(selector))
}
/* ------------------------------------------------------------------------- */
/**
* Retrieve the currently active element
*
* @return Element
*/
export function getActiveElement(): HTMLElement | undefined {
return document.activeElement instanceof HTMLElement
? document.activeElement
: undefined
}