Skip to content

Instantly share code, notes, and snippets.

@oze4
Last active March 16, 2023 23:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save oze4/990e0846b0b535785b3f34c5df89be5e to your computer and use it in GitHub Desktop.
Save oze4/990e0846b0b535785b3f34c5df89be5e to your computer and use it in GitHub Desktop.
Essentially querySelectorAll with regex support. Modified from: https://stackoverflow.com/a/62144522
/**
* @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