Skip to content

Instantly share code, notes, and snippets.

@shitalm
Created August 20, 2020 08:27
Show Gist options
  • Save shitalm/675f3c7b572fd284054789a256eda209 to your computer and use it in GitHub Desktop.
Save shitalm/675f3c7b572fd284054789a256eda209 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