Skip to content

Instantly share code, notes, and snippets.

@guiseek
Created July 10, 2022 08:15
Show Gist options
  • Save guiseek/7506200371ea3f912ecbe58faacb3681 to your computer and use it in GitHub Desktop.
Save guiseek/7506200371ea3f912ecbe58faacb3681 to your computer and use it in GitHub Desktop.
Document Query Selector Typed and Simplified. Ex.: `query<'nav'>('.navigation')`
export type IdSelector =
| `#${string}`
| `#${string} ${string}`
| `#${string} > ${string}`
| `${string}#${string}`;
export type ClassSelector =
| `.${string}`
| `.${string} .${string}`
| `.${string} > .${string}`
| `${string}.${string}`;
export type AttributeSelector =
| `[${string}]`
| `[${string}] ${string}`
| `[${string}] > ${string}`
| `${string}[${string}]`;
type Selector = AttributeSelector | ClassSelector | IdSelector;
type ElementType = HTMLElement | SVGElement;
type KeyOfElementMap = keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap;
type ElementTagNameMap<TagOrSelector> =
TagOrSelector extends keyof HTMLElementTagNameMap
? HTMLElementTagNameMap[TagOrSelector]
: TagOrSelector extends keyof SVGElementTagNameMap
? SVGElementTagNameMap[TagOrSelector]
: TagOrSelector extends Selector
? HTMLElement
: null;
export function query<Tag extends KeyOfElementMap>(
selector: Tag | Selector,
parentElement: ElementType = document.body
) {
return parentElement.querySelector(selector) as ElementTagNameMap<Tag>;
}
export function queryAll<Tag extends KeyOfElementMap>(
selector: Tag | AttributeSelector | ClassSelector | IdSelector,
parentElement: ElementType = document.body
) {
return parentElement.querySelectorAll(selector) as NodeListOf<
ElementTagNameMap<Tag>
>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment