Created
August 29, 2022 06:57
-
-
Save FaberVitale/9c4c6f90a912e458947d17d57d94df0e to your computer and use it in GitHub Desktop.
Simple selector function useful in testing environments. Throws error to indicate that the test has failed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Locates a descendant of `rootElement` given selector provided | |
* or throws error if output element is not found | |
* or is not an instance of input `DomElementClass`. | |
* | |
* ### Example | |
* | |
* ```ts | |
* const btn = queryElement( | |
* renderRes.container, | |
* 'button[type="submit"]', | |
* HTMLButtonElement | |
* ); | |
* ``` | |
* | |
* @param rootElement | |
* @param selector | |
* @param DomElementClass | |
* @returns | |
*/ | |
function queryElement<Elem extends Element>( | |
rootElement: Element, | |
selector: string, | |
DomElementClass: new () => Elem | |
): Elem { | |
const output = rootElement.querySelector(selector); | |
if (!(output instanceof DomElementClass)) { | |
throw new Error( | |
`queryElement ${selector} not found in root ${rootElement.tagName}` | |
); | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment