Skip to content

Instantly share code, notes, and snippets.

@djrobby
Forked from shitalm/queryselector.js
Created December 22, 2022 15:37
Show Gist options
  • Save djrobby/8e2e0b4f4bfbf0b099067e97828aeb59 to your computer and use it in GitHub Desktop.
Save djrobby/8e2e0b4f4bfbf0b099067e97828aeb59 to your computer and use it in GitHub Desktop.
querySelectorAll with regex support
/**
* querySelectorAll with regex support.
* TS version: https://gist.github.com/sagirk/3240407ebbc9369356759a806b66fe34.
*
* 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 {RegExp} regex - A regular expression selector.
* @param {string} attributeToSearch - A specific attribute to search on.
* @returns {Element[]} All element descendants of nodes that match the regex
* selector.
*/
function querySelectorAllRegex(regex, attributeToSearch) {
const output = [];
if (attributeToSearch) {
for (let element of document.querySelectorAll(`[${attributeToSearch}]`)) {
if (regex.test(element.getAttribute(attributeToSearch))) {
output.push(element);
}
}
} else {
for (let element of document.querySelectorAll('*')) {
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