Skip to content

Instantly share code, notes, and snippets.

@sagirk
Last active March 10, 2022 00:01
Show Gist options
  • Save sagirk/3240407ebbc9369356759a806b66fe34 to your computer and use it in GitHub Desktop.
Save sagirk/3240407ebbc9369356759a806b66fe34 to your computer and use it in GitHub Desktop.
`querySelectorAll` with regex support
/**
* querySelectorAll with regex support.
* Adapted from: https://stackoverflow.com/a/62144522.
*
* Note: In the `attributeToSearch` parameter's absence, all attributes on all
* DOM nodes will be searched. This can get quite expensive for large DOM trees.
*
* Usage example:
* `querySelectorAllRegex(/someregex/, 'target-specific-attribute-if-needed');`
*
* @param regex - A regular expression selector.
* @param attributeToSearch - A specific attribute to search on.
* @returns All element descendants of nodes that match the regex selector.
*/
function querySelectorAllRegex(
regex: RegExp,
attributeToSearch?: string
): Element[] {
const output: Element[] = [];
if (attributeToSearch) {
for (let element of document.querySelectorAll<Element>(
`[${attributeToSearch}]`
)) {
if (regex.test(element.getAttribute(attributeToSearch))) {
output.push(element);
}
}
} else {
for (let element of document.querySelectorAll<Element>('*')) {
for (let attribute of element.attributes) {
if (regex.test(attribute.value)) {
output.push(element);
}
}
}
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment