mirror of
https://github.com/squidfunk/mkdocs-material.git
synced 2026-08-01 02:08:46 -04:00
Added method to retrieve element or throw
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user