-
-
Save djrobby/8e2e0b4f4bfbf0b099067e97828aeb59 to your computer and use it in GitHub Desktop.
querySelectorAll with regex support
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
/** | |
* 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