Last active
March 16, 2023 23:30
-
-
Save oze4/990e0846b0b535785b3f34c5df89be5e to your computer and use it in GitHub Desktop.
Essentially querySelectorAll with regex support. Modified from: https://stackoverflow.com/a/62144522
This file contains 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
/** | |
* @plug | |
* DOMRegex.js | |
* https://mattoestreich.com | |
* | |
* @description | |
* Modified from: https://stackoverflow.com/a/62144522 | |
* TLDR; querySelectorAll with regex support | |
* | |
* @important | |
* *** If the `attribute` parameter IS NOT supplied, we search ALL attributes on ALL DOM nodes!*** | |
* | |
* @example | |
* Consider the following: | |
* `<div data-foo="bar"></div>` | |
* If you wanted to target that node: | |
* `document.DOMRegex(/bar/gm, "data-foo");` | |
* | |
* | |
* @param {Regular Expression} regex Regex string | |
* @param {String} attribute The attribute you wish to search | |
*/ | |
document.DOMRegex = (regex, attribute = undefined) => { | |
const output = []; | |
if (attribute === undefined) { | |
for (let element of document.querySelectorAll("*")) { | |
for (let elattribute of element.attributes) { | |
const { name, value } = elattribute; | |
if (regex.test(value)) { | |
output.push({ | |
element, | |
attribute: { name, value }, | |
}); | |
} | |
} | |
} | |
return output; | |
} | |
for (let element of document.querySelectorAll(`[${attribute}]`)) { | |
const name = attribute; | |
const value = element.getAttribute(name).toString(); | |
if (regex.test(value)) { | |
output.push({ | |
element, | |
attribute: { name, value }, | |
}); | |
} | |
} | |
return output; | |
}; // end domRegex.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment