Created
July 10, 2022 08:15
-
-
Save guiseek/7506200371ea3f912ecbe58faacb3681 to your computer and use it in GitHub Desktop.
Document Query Selector Typed and Simplified. Ex.: `query<'nav'>('.navigation')`
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
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