Skip to content

Instantly share code, notes, and snippets.

@esamattis
Last active August 12, 2024 09:39
Show Gist options
  • Save esamattis/532f0f6648e74e7237d9bbd9fc54d681 to your computer and use it in GitHub Desktop.
Save esamattis/532f0f6648e74e7237d9bbd9fc54d681 to your computer and use it in GitHub Desktop.
jsdoc type guards for dom elements
/**
* @template {keyof HTMLElementTagNameMap} T
* @param {any} el
* @param {T} elName
* @returns {el is HTMLElementTagNameMap[T]}
*/
function isElement(el, elName) {
return el?.constructor?.name === elName;
}
/**
* @param {any} el
* @returns {el is HTMLElement}
*/
function isHTMLElement(el) {
const name = el?.constructor?.name;
if (!name) {
return false;
}
if (name === "HTMLElement") {
return true;
}
return isHTMLElement(Object.getPrototypeOf(el));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment