Skip to content

Instantly share code, notes, and snippets.

@MatthewDaniels
Last active October 16, 2020 00:16
Show Gist options
  • Save MatthewDaniels/4ea02d91c8e3c18df3abef1c0c0b8d15 to your computer and use it in GitHub Desktop.
Save MatthewDaniels/4ea02d91c8e3c18df3abef1c0c0b8d15 to your computer and use it in GitHub Desktop.
Gets a DOM element by attribute, matching to regular expression to allow for more complex selectors.
/**
* Get Dom Element with Regex - matches regular expression against the attribute value.
*
* @param regex Regex The regular expression to match the attribute value on
* @param selectorStr String An optional string to further refine the initial selector (used in the querySeelctorAll) - @default *
*
* @return array of objects containing the element, the attriube name and value OR null if none are matched.
*/
function getDomElementWithRegex(regex, selectorStr) {
if(!regex) return null;
selectorStr = selectorStr || '*';
var selectedElements;
var allElements = document.querySelectorAll(selectorStr);
if(allElements.length) {
for (var elIndex = 0, elLen = allElements.length; elIndex < elLen; elIndex++) {
var element = allElements[elIndex];
if(element && element.attributes) {
for (var attrIndex = 0, attrLen = element.attributes.length; attrIndex < attrLen; attrIndex++) {
var attr = element.attributes[attrIndex];
if(regex.test(attr.value)) {
selectedElements = selectedElements || [];
selectedElements.push({
element: element,
attrName: attr.name,
attrVal: attr.value
});
}
}
}
}
}
return selectedElements;
}
@MatthewDaniels
Copy link
Author

Could probably optimize this, but was a quick and dirty solution.

Could iterate this to include an attribute name filtering mechanism also (ie: match only on a specific attribute name and value eg: action & url for form submission).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment