Skip to content

Instantly share code, notes, and snippets.

@JadeMin
Created October 4, 2024 03:36
Show Gist options
  • Select an option

  • Save JadeMin/272e74d70bb6facbdc249d50e06c3aa7 to your computer and use it in GitHub Desktop.

Select an option

Save JadeMin/272e74d70bb6facbdc249d50e06c3aa7 to your computer and use it in GitHub Desktop.
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