Skip to content

Instantly share code, notes, and snippets.

@guiseek
Last active May 16, 2022 23:12
Show Gist options
  • Save guiseek/90d7a91c8e6e17c03f499dc21db3c1c4 to your computer and use it in GitHub Desktop.
Save guiseek/90d7a91c8e6e17c03f499dc21db3c1c4 to your computer and use it in GitHub Desktop.
/**
* You may copy, distribute and modify the software
* as long as you track changes/dates in source files.
*
* Guilherme Siquinelli <[email protected]>
* Copyleft (ↄ) 2022 - LGPL-3.0
*/
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}]`
/**
* You may copy, distribute and modify the software
* as long as you track changes/dates in source files.
*
* Guilherme Siquinelli <[email protected]>
* Copyleft (ↄ) 2022 - LGPL-3.0
*/
export function query<Tag extends keyof SVGElementTagNameMap>(
selector: Tag | AttributeSelector | ClassSelector | IdSelector,
parentElement?: HTMLElement
): SVGElementTagNameMap[Tag]
export function query<Tag extends keyof HTMLElementTagNameMap>(
selector: Tag | AttributeSelector | ClassSelector | IdSelector,
parentElement?: HTMLElement
): HTMLElementTagNameMap[Tag]
export function query<
Tag extends keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap
>(
selector: Tag | AttributeSelector | ClassSelector | IdSelector,
parentElement: HTMLElement | SVGElement = document.body
) {
return parentElement.querySelector(selector)
}
export function queryAll<Tag extends keyof SVGElementTagNameMap>(
selector: Tag | AttributeSelector | ClassSelector | IdSelector,
parentElement?: HTMLElement
): NodeListOf<SVGElementTagNameMap[Tag]>
export function queryAll<Tag extends keyof HTMLElementTagNameMap>(
selector: Tag | AttributeSelector | ClassSelector | IdSelector,
parentElement?: HTMLElement
): NodeListOf<HTMLElementTagNameMap[Tag]>
export function queryAll<
Tag extends keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap
>(
selector: Tag | AttributeSelector | ClassSelector | IdSelector,
parentElement: HTMLElement | SVGElement = document.body
) {
return parentElement.querySelectorAll(selector)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment