Created
October 4, 2024 03:36
-
-
Save JadeMin/272e74d70bb6facbdc249d50e06c3aa7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class DOMQueryError extends Error { | |
| /** @param {string} message */ | |
| constructor(message) { | |
| super(message); | |
| this.name = "DOMQueryError"; | |
| } | |
| } | |
| class DOMTypeError extends Error { | |
| /** @param {string} message */ | |
| constructor(message) { | |
| super(message); | |
| this.name = "DOMTypeError"; | |
| } | |
| } | |
| /** | |
| * @template T should be a subclass of HTMLElement | |
| * @param {string} selector | |
| * @param {{ new (): T }} typeInstance | |
| * @returns {T} | |
| */ | |
| export function querySelector_s(selector, typeInstance) { | |
| const element = document.querySelector(selector); | |
| if (element === null) { | |
| throw new DOMQueryError(`Cannot find element by selector: "${selector}"`); | |
| } | |
| if (!(element instanceof typeInstance)) { | |
| throw new DOMTypeError(`"${selector}": Expected <${typeInstance.name}>, but <${element.constructor.name}>`); | |
| } | |
| return element; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment